jQuery Rollovers Using “this”

webadmin's picture
Coding
JQuery Rocks

jQuery Rollovers Using “ this ” If you’ve been programming in PHP, or other object oriented languages, you may have come across “this” or “self”. With jQuery, we can write $(this) to select an element in the DOM (Document Object Model). The best way to demonstrate this is with a simple example.

Let’s write a short script to do the classic image rollover:

$(function() {
$("#menu img").hover(function() {
$(this).attr("src", $(this).attr("src").split(".").join("-hover."));
}, function() {
$(this).attr("src", $(this).attr("src").split("-hover.").join("."));
});
});

You might have your markup something like this:

So what does the code do? Firstly, we initialize the document.ready() function - using the shorthand notation. You can read more about this in the 1st jQuery tutorial. Within this function, we attach the “hover” event to the images which together create the menu. You can see in the sample HTML markup that there are 3 images. These images are contained within unordered list elements.

Look one line down from where we attach the hover event and you’ll see:

$(this).attr("src", $(this).attr("src").split(".").join("-hover."));

This is where things start to get interesting. $(this) is referencing the image that is hovered over. So couldn’t we have just written $(”#menu img”) instead of $(this)? Well… no. This is because $(”#menu img”) will select all the images instead of just the image that is being hovered over. We could have added a unique class (or ID) to each image and then have selected that for each image. The problem with this is that it involves a whole lot more of unnecessary code. We’d need to attach the hover event to each image.

The next part of that line is: “.attr(…)”. We can use this to change a property to a defined value. We can also use this to get the value of a defined property. For example, the following code changes the SRC property to “foo.gif”:

$("img#example").attr("src", "foo.gif");

We can also assign the current value of the SRC property to a variable by writing:

var srcValue = $("img#example").attr("src");

In the rollover code, we use both. We assign the SRC property a new value by taking the current value, splitting it at the “.” (period) and joining “-hover.” onto the end. You can read more about the “split” function. Essentially, this function splits a string into an array at the delimiter. In this case, we define the “.” (period) as the delimiter.

We pretty much do the reverse for when the cursor moves off the image. We define the delimiter as “-hover.”, thus removing these characters from the SRC property.

Baca Juga

12 years 5 months ago
12 years 4 months ago