Calling a function in a document.
No, you cannot do that, because the onclick handler uses eval()
javascript to evaluate the expression and eval()
expects MyFunction()
it to be a global function, and when it is defined inside the handler .ready()
, it is not a global function, so it eval()
cannot find it.
You can make MyFunction a global function by defining it in the ready () handler as follows:
window.MyFunction = function() {...}
But it would be better to just use jQuery event handlers and not specify the event handler in HTML.
<a id="myLink" href="#">Click Me</a>
$(document).ready(function() {
$("#myLink").click(function() {
alert("Hello");
});
});
source to share
"javascript:" is not needed. And yes you can. As long as you define it in an accessible scope (in other words, a global scope).
function example() { console.log("Called!"); }
$(document).ready(function() { /* code */ example(); /* code */ });
<a href="#" onclick="example();">Example</a>
source to share
If you're trying to get your code out of the global scope, you can do something like this:
var myApp = {
myFunction: function() {
alert("Hello");
}
};
$(document).ready(function() {
myApp.myFunction();
});
However, you will not be able to call the functions defined in the anonymous function because they are both unavailable and inaccessible.
In short, you cannot call a function from outside document.ready if that function is defined in document.ready.
source to share