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 :)
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).
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).
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 });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With