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:
<ul id="menu"> <li><a href="#"><img src="item1.gif" /></a></li> <li><a href="#"><img src="item2.gif" /></a></li> <li><a href="#"><img src="item3.gif" /></a></li> </ul>
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.

August 13, 2008
Quote
Dude..thanks! I have been looking for this and yours is the simplest and best way I have found!
August 17, 2008
Quote
Great write up Michael. I think what was news to me (I am a newbie in both jQuery and web programming) is the concept of defining a handler for the group of dom elements and using the $(this) to actually execute against the individual element.
This is like the construct in .Net where we establish a generic event handler and wire it to several components. But then we have to ferret out which component was actuated when the event fired which is a bit clumsy. Here “this” makes that so simple!
Thanks again,
John
August 19, 2008
Quote
Nice and to the point article, thanks. Looks like jQuery has some great potential that I’ve been missing out on!
August 26, 2008
Quote
No problem guys! I’m glad that you found the tutorial useful.
August 30, 2008
Quote
Homar, please post new stuffs!
I like this blog and the posts you do.
Continue with your great job!
David Carreira
September 13, 2008
Quote
More articles are coming I promise
September 17, 2008
Quote
More articles, pleaseeeeee
David Carreira
September 23, 2008
Quote
Very good blog, I’ve added to my feed reader!
Thank you very much and keep up the good work!
September 30, 2008
Quote
Beautiful website and extremely helpful explanation. I’m going to be using this a lot. THANK YOU from a jQuery newbie!
October 8, 2008
Quote
Very efficient code.
How would it work if I wanted to add a ‘.click’ event and keep the hover image highlighted?
November 2, 2008
Quote
hey, the code rocks. love it. u’re a genius. and the site rocks too. just love it
February 18, 2009
Quote
There is a VERY simple way to create rollover without any javascript at all. Simply CSS and HTML.
Let’s say that your rollover image is 25px tall… In your graphics program you would make your canvas 50px tall and stack the normal image and the rollover image on top of each other:
—————
- nomal image -
—————
- hover image -
—————
Save that as one file.
Imagine an image that is a link… you would use the following HTML:
When you rollover your link, it will move the image up 25 pixels so that the bottom 25px; of the image will display in the link area.
February 18, 2009
Quote
okay… so this forum doesn’t allow HTML….
The link would just be an empty anchor tag
(a href=’#’ style=’background-image: url(image.gif)’)(/a)
February 18, 2009
Quote
Sorry Joe. I have now edited your post to show the HTML. Whilst this can be done in CSS, you’d need to use display:block on the link element to get it working in IE6. You’d also need to make the parent container position:relative and assign a higher z-index to #exampleLink:hover.
The best way to go about this is to shift the background image on hover. However, the purpose of this article is really to demonstrate the use of $(this) in jQuery rather than the different solutions available to create rollovers.
March 27, 2009
Quote
This is a great script. How do I get it to work as an external .js file. I can only get it to work when I include the entire script within the tags of the relevant HTML page. If I try to link to it as an external js file it loses its functionality?
March 27, 2009
Quote
My apogogies. Made a stu-pid mistake nothing to do with this script. Have I already said this script is awesome? Great for dynamically loading images
June 10, 2009
Quote
Hello,
One thing i would like to understand about this tutorial.
when you put (”-hover.”)…is the “-hover” part of the image name? for instance you have “image.jpg” for the regular state, and “image-hover.jpg” for the hover state?