Reputation: 713
Looking at When should I use jQuery's document.ready function? and Form submit button onclick does not call my JS function gives a sense that using $document.ready(function(){})
should have no harm in the code, rather it is for the good.
But when I enter a function into the onclick
method of button, the functions inside ready()
statement don't get executed. Why so?
As an example, this code does not give an alert
$(document).ready(function(){
function f(){
alert("alert");
}
})
/*function f(){
alert("alert");
} */
<button onclick="f()">
My Button
</button>
I understand that if I use the jQuery selectors to make it work, it will ($("button").click(f)
). But why does this method fail?
Upvotes: 1
Views: 1755
Reputation: 117
$(document).ready() gets called after all of your html has finished loading. Since you are calling the "f()" function within your html, it calls "f()" before anything in "$(document).ready()" has run yet, meaning there is no definition for "f()".
It is common now to not even use "$(document).ready()" as long as you are loading that jQuery at the end of all of your html to avoid long load times. This will allow you to call "f()" from within your html and still have the rest of your jQuery load after your html.
Upvotes: 0
Reputation: 187124
Anytime you declare a function you create a scope. Anything declared inside that scope is not accessible outside that scope.
$(document).ready(function(){
// f is only accessible to other code declared in this function.
function f(){
alert("alert");
}
})
The recommended way to do this with jQuery is to assign the on click handler function in the jQuery ready function.
HTML:
<button id="my-button-id">My Button</button>
Javascript:
$(document).ready(function(){
// f is only accessible to other code declared in this function.
function f(){
alert("alert");
}
// Assign onclick here
$('#my-button-id').on('click', f)
})
Upvotes: 1
Reputation: 113944
It's a problem of scope - functions declared inside functions is not accessible outside the outer functions just like variable declared inside functions:
(function(){
var a = 'hello';
function b () {
console.log(a);
}
})();
a; // syntax error - a is undefined
b(); // syntax error - b is undefined
You can make it work by assigning the function to a global variable:
var f;
$(document).ready(function(){
f = function(){
alert("alert");
}
})
Upvotes: 4