Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can I not define functions in jQuery's document.ready()?

Functions come up as undefined if I place them in the document.ready() function:

$(document).ready(function(){   function foo()   {     alert('Bar');   } });  foo(); // Undefined 

Why does this happen? I'm sure I'm just in need of some simple understanding :)

like image 924
James Skidmore Avatar asked Jun 28 '09 21:06

James Skidmore


People also ask

What is difference between $( function () and document Ready?

There is no difference in functionality between your examples - they both bind to DOM ready. For reference, there are two points at which you can bind your jQuery code. The first will execute when the DOM is ready (both are equivalent): // full example $(document).


2 Answers

Not sure why defining the function with in the scope of ready() is important to you, but you can make it work by declaring foo up front:

<html><head> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.1/jquery.min.js"></script> <script> var foo;                           // Here's the difference $(document).ready(function(){   foo = function ()   {     alert('Bar');   } }); </script></head><body> <input type="button" onclick="foo()" value="Click me"> </body></html> 

Obviously you can't call foo() from the inline script immediately after ready() because the ready() code hasn't yet run, but you can call the function later on.

Just make sure that nothing can try to call foo() before the ready() code has run (or make the initial declaration of foo() a harmless function).

like image 197
RichieHindle Avatar answered Oct 21 '22 11:10

RichieHindle


You can but they must be called within the scope of the ready() method otherwise they lose scope when the ready() method exits.

For example, the code below will work:

$(document).ready(function(){   function foo()   {     alert('Bar');   }    foo(); // still in the scope of the ready method }); 
like image 39
Soviut Avatar answered Oct 21 '22 10:10

Soviut