Why can I not define functions in jQuery's document.ready()?
JavascriptJqueryJavascript Problem Overview
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 :)
Javascript Solutions
Solution 1 - Javascript
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).
Solution 2 - Javascript
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
});
Solution 3 - Javascript
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.
Solution 4 - Javascript
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.
Solution 5 - Javascript
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().
Solution 6 - Javascript
<script>
$(document).ready(function(){
myfnc = function (param1, param2)
{
alert('Hello');
}
myfnc();
});
</script>
<input type="button" onclick="myfnc('arg1', 'arg2')" value="Click me">