Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call function in document.ready

Tags:

jquery

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>
like image 370
user973063 Avatar asked May 31 '26 11:05

user973063


2 Answers

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");
    });
});
like image 126
jfriend00 Avatar answered Jun 02 '26 01:06

jfriend00


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>
like image 21
Corbin Avatar answered Jun 02 '26 01:06

Corbin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!