Malik Daud Ahmad Khokhar
Malik Daud Ahmad Khokhar

Reputation: 13720

How to call multiple js functions on document.ready without putting them jQuery(document).ready(function(){});

Is there a way to 'bind' multiple functions to jQuery's document.ready function without actually calling them in that method. Basically I don't know which functions I might be calling in document.ready until the page is generated.

Upvotes: 1

Views: 5088

Answers (4)

Matt
Matt

Reputation: 41832

If you call $(document).ready() anytime after the document was already ready, it will just execute immediately: (http://jsfiddle.net/Ew8b3/)

var afterReady = function(){
    $(document).ready(function(){
      $('body').append('<div>waited 5 secs</div>');
    });
};

$(document).ready(function(){
  setTimeout(afterReady, 5000);
});

I'm not sure how/when you will know what you want to execute, but know that you can use document.ready at any time.

Upvotes: 1

mrBorna
mrBorna

Reputation: 1777

I'm not sure I quite understand what you mean by bind without calling. But what you can do is pass the functions in as variables (for example func1, and func2)

this way you can do something like:

$(document).ready(function() { 
                      var func1 = ...;
                      var func2 = ...;
                      doSomething(func1,func2);
}

doSomething(f1,f2){
   return f1()+f2("somedata");
   // or whatever you wanna do
}

Upvotes: 0

John Fisher
John Fisher

Reputation: 22719

There are several ways to handle this. (You probably want #2.)

  1. Use an options class to determine what happens, then have static code which checks the options to see which functions to call.

  2. Wait until you know what functions to call, and add each of them into $(document).ready(whatever) as separate lines.

    $(document).ready(function1);
    $(document).ready(function8);
    
  3. Dynamically create the body of the one function you write into $(document).ready(...)

Upvotes: 5

Nathan Romano
Nathan Romano

Reputation: 7096

$(function() { alert('ready'); });

is the same as

Jquery(document).ready(function() { alert('ready'); }):

Upvotes: -2

Related Questions