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

Functions appear as undefined if I put them in the document.ready () function:

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

Why is this happening? I'm sure I just need some understanding :)

+56
javascript jquery
Jun 28 '09 at 21:02
source share
6 answers

I don’t know why it is important to define a function in the ready() scope, but you can make it work by declaring foo in 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 the difference $(document).ready(function(){ foo = function () { alert('Bar'); } }); </script></head><body> <input type="button" onclick="foo()" value="Click me"> </body></html> 

Obviously, you cannot call foo() from the built-in script right after ready() , because the ready() code is not already running, but you can call the function later.

Just make sure nothing can try calling foo() before running ready() code (or making the initial declaration of foo() harmless function).

+60
Jun 28 '09 at 21:15
source share

You can, but they must be called as part of the ready() method, otherwise they lose scope when the ready() method completes.

For example, the code below will work:

 $(document).ready(function(){ function foo() { alert('Bar'); } foo(); // still in the scope of the ready method }); 
+23
Jun 28 '09 at 21:05
source share

They will appear as undefined if you place them in any area that does not belong to them. If you really want to use them outside of $ (document) .ready (...), you need to declare them from the outside. For example:

 var foo; $(document).ready(function(){ foo = function() { alert('Bar'); } }); foo(); // works now because it is in scope 

Hope this helps.

+5
Jun 28 '09 at 21:18
source share

Your function is defined in the $(document).ready() callback area and cannot be seen externally. Or define a function outside the scope of $(document).ready() to call it only from the inside.

+4
Jun 28 '09 at 21:06
source share
 <script> $(document).ready(function(){ myfnc = function (param1, param2) { alert('Hello'); } myfnc(); }); </script> <input type="button" onclick="myfnc('arg1', 'arg2')" value="Click me"> 
+1
Sep 06 '14 at 7:01
source share

Another addition:

When functions or variables are declared inside the $(document).ready() function, they are not available when using onclick() bindings in a document.

You can move ads outside of $(document).ready() , or you can use $('#element').on('click', function() {}) inside `$ (document) .ready ().

0
Sep 07 '16 at 9:54 on
source share



All Articles