Question

I'm currently working my way through Learning jQuery by Karl Swedberg where all jQuery code samples in the book are contained in $(document).ready().

While i understand why the code has to be contained in $(document).ready(),namely so that they will be run only when the HTML document has loaded, the book does not explain why any code has to be placed inside a function.

E.g

$(document).ready(function(){
    alert("The page has loaded.");
    alert("2nd alert.");
});

In the example above, why does the alert have to be contained in a function() to work, and cannot an example like the one below will not work.

$(document).ready(
    alert("The page has loaded.");
    alert("2nd alert.");
);

I would appreciate if anyone can enlighten me.

Was it helpful?

Solution 2

$(document).ready accepts a callback. A callback is a javascript function. Javascript functions can be passed around just like variables. In the case above you are using an inline anonymous function, that is a function with no name.

You could rewrite your example like this:

function doStuff() {
    alert("The page has loaded.");
    alert("2nd alert.");
}

$(document).ready(doStuff);

You need to use a function because you cannot pass statements as parameters to a function but you can pass a function.

Note if you don't want to have to type as much there is a shorthand notation that is functionally equivalent:

$(function() {
    alert("The page has loaded.");
    alert("2nd alert.");
});

or without the inline function:

function doStuff() {
    alert("The page has loaded.");
    alert("2nd alert.");
}

$(doStuff);

OTHER TIPS

Reads Docs, it specify a function to execute when the DOM is fully loaded.

.ready( handler )

Where, handler

Type: Function()

A function to execute after the DOM is ready.

$(document).ready() expects a function. Your second example is actually a syntax error, since alert("The page has loaded."); alert("2nd alert."); is not a valid parameter list.

The reason you typically have to use $(document).ready() in jQuery is because you are usually interacting with DOM nodes (which aren't actually available in the DOM yet if your script happens to be at the top of the page). An alternative is to put your script at the bottom of the page, at which point all of the DOM nodes you need are available, and there's no need for the $(document).ready() wrapper.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top