Why can I not define functions in jQuery's document.ready()?
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
});
They will come up as undefined if you put them in any scope that is not theirs. If you really want to use them outside of the scope of $(document).ready(...) then you need to declare them externally. Such as:
var foo;
$(document).ready(function(){
foo = function()
{
alert('Bar');
}
});
foo(); // works now because it is in scope
Hope this helps.
Your function is defined within the scope of the $(document).ready()
callback and cannot be seen from the outside. Either define the function outside the $(document).ready()
scope of call it only from within.
Just another addition:
When declaring functions or variables inside of the $(document).ready()
function, these are inaccessible when using onclick()
binds in the document.
You can either move your declarations outside of $(document).ready()
, or you can use $('#element').on('click', function() {})
within `$(document).ready().