[ACCEPTED]-How to call a function within $(document).ready from outside it-function

Accepted answer
Score: 68

Define the function on the window object 2 to make it global from within another function 1 scope:

$(document).ready(function(){  
  window.lol = function(){  
    alert('lol');  
  }  
});
Score: 37

Outside of the block that function is defined 7 in, it is out of scope and you won't be 6 able to call it.

There is however no need 5 to define the function there. Why not simply:

function lol() {
  alert("lol");
}

$(function() {
  lol(); //works
});

function dostuff(url) {
  lol(); // also works
}

You 4 could define the function globally like this:

$(function() {
  lol = function() {
     alert("lol");
  };
});
$(function() {
  lol();
});

That 3 works but not recommended. If you're going 2 to define something in the global namespace 1 you should use the first method.

Score: 3

You don't need and of that - If a function 6 is defined outside of Document.Ready - but 5 you want to call in it Document.Ready - this 4 is how you do it - these answer led me in 3 the wrong direction, don't type function 2 again, just the name of the function.

      $(document).ready(function () {
     fnGetContent();
      });

Where 1 fnGetContent is here:

       function fnGetContent(keyword) {
            var NewKeyword = keyword.tag;
            var type = keyword.type;
            $.ajax({ .......
Score: 2

Short version: you can't, it's out of scope. Define 1 your method like this so it's available:

function lol(){ 
  alert('lol'); 
} 

$(function(){
  lol();
});
Score: 0

What about the case where Prototype is installed 3 with jQuery and we have noconflicts set 2 for jQuery?

jQuery(document).ready(function($){  
     window.lol = function(){  
          $.('#funnyThat').html("LOL");
     }  
});

Now we can call lol from anywhere 1 but did we introduce a conflict with Prototype?

More Related questions