jQuery - function inside $(document).ready function

78,227

Solution 1

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';

Solution 2

This will also work.

$(document).ready(function() {
      callMe = function() {
            alert('hello');
      }
});

callMe();

If you use

 var callMe = function () { ... }

It may not work and you may get an error "function is undefined"

Solution 3

You can do like that:

$(document).ready(function(){

    var callMe = function(){
       //enter code here
    }

    $(".my-class").on("click", function(){
       callMe();
    });

});

So, you don't need to put the function outside the document ready and the code becomes grouped and more organized. ;)

Solution 4

When you create a function inside $(document).ready, it's guaranteed that it won't be called before the document has loaded. Of course, it can only be called from that event handler itself (somewhere later in the event handler).

In other words, what you're trying to do is valid (though not necessarily desirable - you'd have to reveal more about what you are trying to accomplish).

Solution 5

It is probably a better idea to call the function directly like so:

$(document).ready(myFunction);

function myFunction() {

   // Your code here

}
Share:
78,227
user398341
Author by

user398341

Updated on July 21, 2022

Comments

  • user398341
    user398341 almost 2 years

    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++).

  • GalacticCowboy
    GalacticCowboy almost 13 years
    And would it even execute his internal function? It's just declaring it, but does nothing with the declaration so it wouldn't have any effect. ??
  • Mike Richards
    Mike Richards almost 13 years
    Exactly, it just defines, and doesn't call it. I can't think of a reason you would want to delay the definition of a function?
  • user398341
    user398341 almost 13 years
    The reason why I want to put it inside of the ready() method is because it uses some of the variables defined within ready(), to which I wouldn't have an access if the function is declared outside of ready(). These variables are changing depending on different behaviours and this specific function might be called on a number of different occasions.
  • Mike Richards
    Mike Richards almost 13 years
    If you're saying that the ready() function creates global variables, it still doesn't matter if you define the function within ready(), or outside of it. As long as your implementation of it gets run at the correct moment, your function can use the global variables defined in ready()
  • user398341
    user398341 almost 13 years
    Do you think that passing parameters to this function rather than having it declared inside of ready() method would be a better option?
  • user398341
    user398341 almost 13 years
    I didn't know you can use variables declared inside of one function in the other - I'll give it a try and see if it works.
  • GalacticCowboy
    GalacticCowboy almost 13 years
    @user398341 - without a better understanding of what you're trying to do, it's tough to say. However, it sounds like you believe that anything declared outside of $(document).ready will be executed immediately, even if the document isn't ready. Your function will only be executed when it is called, whenever/wherever that happens to be.
  • user398341
    user398341 almost 13 years
    It doesn't seem to be working - here's what I've got: $(function(){ var ind = 0; and then before that function() { ind++; } - but as I thought - it doesn't seem to work...
  • user398341
    user398341 almost 13 years
    That's not quite what I think and what I'm trying to do. Function which is declared outside of ready() uses variables declared inside of the ready(function() therefore I have no access to those variables if function is declared outside. I believe the only other option is to pass parameters to the function() outside of dom
  • Mike Richards
    Mike Richards almost 13 years
    Right, variables cannot be declared globally within a function, unless you define it like window.yourVariable = ''; The other option is to put var yourVariable; before ready(), and then within ready() { yourVariable = 'whatever'; }
  • user398341
    user398341 almost 13 years
    Will this option be better rather than including function within ready() - I've heard that using global variables isn't a great approach - but then again - I don't quite know why.
  • Mike Richards
    Mike Richards almost 13 years
    Yes, if at all possible, I would say try to avoid global variables. The reason being because it gets MESSY. If you have multiple functions read/writing to it, things can get hairy fast. With that being said, there are ways to organize global variables better, such as object literals, which can help group functionality and properties.
  • user398341
    user398341 almost 13 years
    Thanks Mike - I think I need to dedicate some time to learn Object Oriented Javascript. Thanks for your help - it seems there's no better way forward.
  • Joel Peltonen
    Joel Peltonen about 11 years
    "it's better to define them outside of document ready" I can't say that I disagree, but why is this? Is there an actual reason that helps the page render faster or the JS to execute quicker or some other reason. I would kind of think that delaying JS execution would actually be a good thing.
  • mattshu
    mattshu almost 4 years
    You could make the event a one-liner: $(".my-class").on("click", callMe);