Liquee
Liquee

Reputation: 13

jQuery global object doesn't work inside function

Can any anyone tell me why the example below doesn't work:

var obj = $('#example');

function examplefunc(){
    obj.hide();
}

Whilst the second one works fine:

function examplefunc(){
    var obj = $('#example');

    obj.hide();
}

I know that the difference is obvious - in first example we have global variable, whilst in second we have local one. But yet another example shows that global string var i accessible inside the function:

var text = "Hello World!"

function examplefunc(){
    alert(text);
}

How can I make a global jQuery object variable visible inside the function in the first example? Is there any limitation of creating and using a global jQuery object? Any solutions?

Upvotes: 1

Views: 624

Answers (1)

Andy E
Andy E

Reputation: 344585

I would hazard my guess that you're executing this line of code:

var obj = $('#example');

Before the element with ID of example is parsed into the DOM by the browser. You can work around it by moving your <script> element to below the #example element in your document, or you can make use of the document ready event:

var obj;

$(function () {  // This function is run after the document is parsed and ready
    obj = $('#example');
});

function examplefunc(){
    obj.hide();
}

Upvotes: 1

Related Questions