Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript function inside document.ready

Why doesn't any javascript function written inside document.ready be directly called from an event in jsp?

Eg:

$(document).ready(function(){
     function abc()
     {
          //Some stuff here
     }
});

From something like:

<input id="a" type="button" onclick="abc();">
like image 482
Pranav Kale Avatar asked Aug 29 '13 07:08

Pranav Kale


People also ask

Can we write function inside $( document ready?

Yes, you can do that, it's just a matter of scope. If you only need to access callMe() from within $(document). ready(function() { }) , then it's fine to put the function there, and offers some architecture benefits because you can't access the function outside of that context.

How do you define a function inside document ready?

The ready() method is used to make a function available after the document is loaded. Whatever code you write inside the $(document ). ready() method will run once the page DOM is ready to execute JavaScript code.

How do you call a function from document ready?

jQuery Document Ready Example ready(function() { //DOM manipulation code }); You call jQuery's $ function, passing to it the document object. The $ function returns an enhanced version of the document object. This enhanced object has a ready() function you can call, to which you pass a JavaScript function.

How do you write a ready function in JavaScript?

$( document ). ready() ready() will only run once the page Document Object Model (DOM) is ready for JavaScript code to execute. Code included inside $( window ). on( "load", function() { ... }) will run once the entire page (images or iframes), not just the DOM, is ready.


1 Answers

Because it's not available in the global scope. Any function defined within the anonymous function you pass as an argument to $.ready() is only available within that function.

To achieve what you want to do you need something like:

$(document).ready(function(){
     function abc() {}

     $('#a').on('click',abc);
});

For more information on function scope see this MDN article

like image 177
Mchl Avatar answered Sep 21 '22 02:09

Mchl