Calling a function in a document.

Is it possible to call a function in document.ready (function () {}) using the onclick ... event?

      document.ready(function(){
      function MyFunction()
                {
                  alert("Hello");
                }
                });

<a href="#" onclick="javascript:MyFunction()"></a>

      

+3


source to share


3 answers


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");
    });
});

      

+10


source


"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>

      

+1


source


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.

0


source







All Articles