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 :)
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:
Hope this helps.
Just another addition:
When declaring functions or variables inside of the
$(document).ready()
function, these are inaccessible when usingonclick()
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().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.Not sure why defining the function with in the scope of
ready()
is important to you, but you can make it work by declaringfoo
up front:Obviously you can't call
foo()
from the inline script immediately afterready()
because theready()
code hasn't yet run, but you can call the function later on.Just make sure that nothing can try to call
foo()
before theready()
code has run (or make the initial declaration offoo()
a harmless function).You can but they must be called within the scope of the
ready()
method otherwise they lose scope when theready()
method exits.For example, the code below will work: