Web Development: Binding Functions in jQuery

Published on Jun 2, 2009   //  Development
Off

Web Development

Last week we talked about how, in jQuery, you reference an object and then build off of it in a “tree”-type fashion. This week we’ll be talking about branching off of the reference.

Once you have something referenced, you can then follow it with a period, and the name of a function you want to execute on the object. Now, some of these functions accept regular attributes, which you can specify within parenthesis. However, some functions also allow you to create a function as one of the attributes. This allows you to execute other Javascript or jQuery commands within the function applied to the referenced object. This is known as binding a function.

A good example of a function that allows you to bind a function to it is ready(). This function will execute the bound function within when the document object model is ready to be manipulated (before images have loaded, which is a key difference from Javascript’s onload. The ready() function is most commonly used on the root document of the page.

Let’s take a look at an example of the ready() function.

[code language="js"]$(document).ready( function() {
alert("The DOM is ready to be manipulated.");
} );[/code]

This bit of script would throw up an alert box as soon as the DOM is ready. Notice how we just create a name-less function within the ready() function. Quotes are not necessary around document, because it isn’t technically an element.

Some functions may also pass attributes to the bound function, which you can reference during the creation of the function, then use those attributes within the function itself. Next week we’ll be going over something closely related to binding function, but with a key difference, callbacks.