Saturday, May 11, 2024
 Popular · Latest · Hot · Upcoming
86
rated 0 times [  91] [ 5]  / answers: 1 / hits: 65194  / 15 Years ago, sun, june 28, 2009, 12:00:00

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


More From » jquery

 Answers
55

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


[#99224] Wednesday, June 24, 2009, 15 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
jaelynncherokeeg

Total Points: 697
Total Questions: 109
Total Answers: 104

Location: France
Member since Thu, Mar 18, 2021
3 Years ago
jaelynncherokeeg questions
Thu, May 27, 21, 00:00, 3 Years ago
Fri, Jan 24, 20, 00:00, 4 Years ago
Thu, Nov 14, 19, 00:00, 5 Years ago
Wed, Sep 18, 19, 00:00, 5 Years ago
;