jQuery - function inside $(document).ready function

user398341 picture user398341 · Jul 21, 2011 · Viewed 71.7k times · Source

Is it correct to create functions inside of

$(document).ready(function() {

like so:

$(document).ready(function() {
     function callMe() {

     }
 });

The function inside of the .ready() does not have to call before DOM is ready and event inside of the ready() is triggered.

Just to clarify a little bit - here's the code which would illustrate the problem:

$(function() {
    var ind = 0;

    // some event is executed and changes the value of the ind

    // another event which affects the ind variable

    // and another one - after this event we call our function


    // there's another event - and we call our function again

The function which I need to call needs the updated value of the ind variable - which I guess I could pass as a parameter, but is there a better way of doing it?

Also - another important thing is that the function() in question can also change the value of the ind variable - for instance incrementing it (ind++).

Answer

Mike Richards picture Mike Richards · Jul 21, 2011

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.

If you need to use the callMe() function outside of document ready though, you need to define the callMe() function outside of that context.

function callMe() {
  // Do Something
}

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

UPDATE

Based on your clarification, you have two options:

1) DECLARE variable outside of ready(), but then define variable inside of ready():

var someVariable;
function callMe() {
  someVariable++;
  alert(someVariable);
}

$(document).ready(function() {
  someVariable = 3;
  callMe(); // Should display '4'
});

2) Within ready(), define variables using window.yourVariable = 'whatever';