views:

521

answers:

3

How do you call function lol() from outside the $(document).ready() for example:

$(document).ready(function(){  
  function lol(){  
    alert('lol');  
  }  
});  

Tried:

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

And simply:

lol();

It must be called within an outside javascript like:

function dostuff(url){
  lol(); // call the function lol() thats inside the $(document).ready()
}
+8  A: 

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

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

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

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

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

You could define the function globally like this:

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

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

cletus
+1  A: 

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

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

$(function(){
  lol();
});
Nick Craver
A: 

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

$(document).ready(function(){  
  window.lol = function(){  
    alert('lol');  
  }  
});
nicerobot