Friday, 22 July 2011

What is "this" in jQuery?

When is this a DOM element?

The short answer is - usually. Scripting with jQuery quite often involves the use of callback functions. Whether handling an event, iterating a collection of nodes, animating an image, or applying a dynamic filter, callbacks are used to invoke your custom code at the appropriate time. To make things easy for you, jQuery sets the scope of the callback function to the element which is the subject of the callback. For example, when we want to handle a mouse click event for an element we bind a handler function to the event like so:


$('#myButton').bind('click', function() {

// our code to handle the click event goes

// here, in the callback function

});


When a user clicks the 'myButton' element, jQuery invokes the callback function that was passed to the bind method. But when it invokes our callback it sets the current scope to the DOM element that initiated the event, in this case the 'myButton' element. jQuery does this as a convenience. The object you are most likely to need in the event callback is the element that triggered the event. And what easier way to have access to it than by using the this keyword? So within the callback function it can be assumed that this is the relevant DOM element.

Converting this to $this

When this is a DOM element it is often in the context of code that needs to access or manipulate it in some way. This, of course, is something that jQuery excels at. So how do we use the power of the jQuery API when this is a DOM element? Just turn this into $this:


$('div').each(function() {

// 'this' is a DOM element

// wrap 'this' in a jQuery object

var $this = $(this);

// now we have the full jQuery API at our disposal

var title = $this.attr("title");

if (title != null)

$this.prepend("<h2>" + title + "</h2>");

});


Click here to read more

No comments:

Post a Comment