If you view the jquery code below you will see the famous $(document).ready(function(){ that starts the script off. I see this on pretty much all jquery code e
First of all, you can shorten that to:
Second, if you want your scripts to run when the page is finished loading, then yes, you need to put them in a jQuery
/document.ready()
function. You can put them all in the same jQuery(function () { })
block though and they'll be executed in order, you don't have to separate them.
To expand on the workings of function() {}
blocks:
jQuery(/* do something */);
means "On page load, do something". That "do something" is a function. You can pass it a function directly like this:
function myFunction() {
...
}
jQuery(myFunction);
You defined a function "myFunction
" and told jQuery to execute it on page load. Note that you just pass the function itself to jQuery, without ()
. If you'd write jQuery(myFunction());
instead, that would execute myFunction()
immediately, and whatever is returned by myFunction()
would be placed in jQuery()
, and that would be executed upon page load. It's a little different from languages like PHP, since in PHP it's desired behaviour to execute everything immediately, in Javascript that is not necessarily so. In PHP you can't pass the function itself around, in Javascript you can. Functions in Javascript act a lot more like variables.
What you usually do is "make up a function on the fly" that contains some block of code that you want executed at a later time:
jQuery(function () {
foo();
bar();
});
In this case you're passing a function as well, just that you made it up on the fly and the function doesn't have a name. jQuery will hold onto this function until page load, at which time it'll execute it. Inside that function you can do as many things as you like.