Reputation: 31
Can I call function in document.ready(function(){ }) by using "onclick" event...?
document.ready(function(){
function MyFunction()
{
alert("Hello");
}
});
<a href="#" onclick="javascript:MyFunction()"></a>
Upvotes: 3
Views: 5525
Reputation: 707158
No, you cannot do that becuase the onclick handler uses eval()
to evaluate the javascript expression and eval()
expects MyFunction()
to be a global function and when it is defined inside the .ready()
handler, it is not a global function so eval()
does not find it.
You can make MyFunction be a global function by defining it in the ready() handler like this:
window.MyFunction = function() {...}
But, it would be better to just use jQuery's event handlers and not specify the event handler in the HTML.
<a id="myLink" href="#">Click Me</a>
$(document).ready(function() {
$("#myLink").click(function() {
alert("Hello");
});
});
Upvotes: 10
Reputation: 34038
If you are trying to keep 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 any functions defined within an anonymous function because they are both out of scope and inaccessible.
So in short, you cannot call a function from outside of document.ready if that function is defined within the document.ready.
Upvotes: 0
Reputation: 33437
The "javascript:" is unnecessary. And yes, you can. As long as you define it in a scope that's accessible (in other words, the global scope).
function example() { console.log("Called!"); }
$(document).ready(function() { /* code */ example(); /* code */ });
<a href="#" onclick="example();">Example</a>
Upvotes: 1