Search code examples
jquery

How to pass multiple functions in document.ready


I want to pass more than one functions on document ready.

Doing something like

$(document).ready(myFunction; anotherFunction;);

did not work.

If I add parentheses, it will actually execute the function.

It works if I do

$(document).ready(myFunction);
$(document).ready(anotherFunction);

but , is there a better syntax where I can pass all the functions at once?

Something like

$(document).ready(myFunction, anotherFunction);

Thanks


Solution

  • document.ready takes a single function as its argument. There is therefore no way to specify all of your functions as a list of parameters. You have a couple of different options for writing it differently with the same behaviour.

    1. Create a new function to wrap your others
    function initialise() {
        myFunction();
        anotherFunction();
    }
    
    $(document).ready(initialise);
    
    1. Use jQuery's $(document).ready shortcut syntax
    $(myFunction);
    $(anotherFunction);
    

    3a) Wrap them all in one function passed to document.ready

    $(document).ready(function () {
      myFunction();
      anotherFunction();
    });
    

    3b) Or equivalently using the shortcut syntax

    $(function() { myFunction(); anotherFunction(); });