35

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

informatik01
  • 16,038
  • 10
  • 74
  • 104
user398341
  • 6,339
  • 17
  • 57
  • 75

9 Answers9

57

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

informatik01
  • 16,038
  • 10
  • 74
  • 104
Mike Richards
  • 5,557
  • 3
  • 28
  • 34
  • 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. ?? – GalacticCowboy Jul 21 '11 at 18:35
  • 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? – Mike Richards Jul 21 '11 at 18:37
  • 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. – user398341 Jul 21 '11 at 19:16
  • 2
    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. – Mike Richards Jul 21 '11 at 19:19
  • 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. – user398341 Jul 21 '11 at 19:23
  • "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. – Joel Peltonen Feb 26 '13 at 08:37
5

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"

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

rntperes
  • 31
  • 1
2

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

$(document).ready(myFunction);

function myFunction() {

   // Your code here

}
soulBit
  • 438
  • 6
  • 15
2

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

Tomas Kohl
  • 1,388
  • 1
  • 19
  • 27
  • Do you think that passing parameters to this function rather than having it declared inside of ready() method would be a better option? – user398341 Jul 21 '11 at 18:48
  • @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. – GalacticCowboy Jul 21 '11 at 18:53
  • 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 – user398341 Jul 21 '11 at 18:57
0

See if you can eliminate the need for using document.ready by moving your tag to the bottom of the html file. This should make things alot simpler. Otherwise, declare the function outside the scope of the document.ready and just call it in the document.ready function scope.

0

You can use like the following:

$(document).ready(function () {
    printReport = function(rowIndex) {
        // Your code here
    }
});

You can call this function from any event.

Corentin Pane
  • 4,794
  • 1
  • 12
  • 29
0

This is definitely legal. The question is why do you want to do it? Probably to bind the function's scope to that of ready and not have it globally bound to the window object. But is that what you really want? I suggest having a look on function closures in javascript and how it handles scoping. to help clarify the need for it...

PhD
  • 11,202
  • 14
  • 64
  • 112
  • 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. – user398341 Jul 21 '11 at 18:43
  • 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() – Mike Richards Jul 21 '11 at 18:48
  • 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. – user398341 Jul 21 '11 at 18:53
  • 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 Jul 21 '11 at 18:55
  • 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'; } – Mike Richards Jul 21 '11 at 19:04
0
<input type="button" value="Click Me!" onclick="Demo();" />


<script>

    $(document).ready(function () {

        Demo = function () {
            alert("Hello World");
        };
    });

</script>
Md Shahriar
  • 2,072
  • 22
  • 11
  • 1
    Your answer could be improved by adding more information on what the code does and how it helps the OP. – Tyler2P Jan 18 '23 at 15:54