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>
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");
});
});
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With