James Skidmore James Skidmore - 2 months ago 5
jQuery Question

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 :)

Answer

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).

Comments