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?
July 26, 2009
Quote
Dude thanks! Such an elegant solution. JQuery is the business!
July 27, 2009
Quote
How would you do this if you wanted to have a 3rd state for click. So you would have an on state, off state and click state with three diffrent images?
Thanks
August 10, 2009
Quote
Great script! I got it working with img tags, but couldn’t do it with td or div tags (to swap background-image). Any hint will be greatly appreciated!
August 14, 2009
Quote
I had the same third state click problem.. This is a tutorial I came across about JQuery rollovers- http://www.ehousestudio.com/bl.....th-jquery/
It was helpful as well. Thanks for the post.
August 25, 2009
Quote
Nice tutorial..
I am trying to fo a menubar in which with the mouse is on the menu a kind of painting will drip down and stop.
can you help me with this pls?
September 28, 2009
Quote
Homer
Nice tutorials. although you don’t have a tutorial on buttons i’m trying to implement I’m still struggling with the submit buttons using the sample you posted but no go
I have added this to my markup
and this is the jquery
$(document).ready(function() {
$(’input[type=”image”]’).hover(
function () { $(this).attr(”src”, $(this).attr(”src”).split(’-off’).join(’-on’)); },
function () { $(this).attr(”src”, $(this).attr(”src”).split(’-on’).join(’-off’)); }
);
});
am i suppose to add css to this for it to work or am i missing something in the jsquery.
Thanks
Andrea
September 28, 2009
Quote
ok > here it
input type=”image” src=”http://domain.com/skins/new/styleImages/buttons/mybutton1.gif” alt=”mybutton” />
Its all there, except the hover won’t work! where is it calling the second file which is the hover state?
September 29, 2009
Quote
Hover does work… excellent function…. i had the in the wrong place
September 30, 2009
Quote
Thanks for the tutorial. It’s exactly what I needed!
October 21, 2009
Quote
Thanks. I tried different methods before, but yours is the simplest I have ever seen!
Keep going!
October 22, 2009
Quote
I am trying to modify the script and can’t get it to work.
I would like the menu to be words (in this case flower names) and popup the image of the named flower when the mouse hovers over the name.
The menu list would be:
Primal Scream
Lake Effect
Taos
and the menu would be links to more information.
Any suggestions?
October 30, 2009
Quote
Thanks for the very informative post. I’ve really got to start using some bits of jQuery in my designs! I’ll be back!
Thanks again!
November 24, 2009
Quote
Thanks for this amazing code! But… how can I add fade while changing the images? I’m trying everything but I’m lost =(
February 25, 2010
Quote
You have really done a great job. Quite inspirational menus indeed. I like it and always appreciate unique designs. Thanks
February 25, 2010
Quote
I was really looking for this query for my website. Thanks for tutorial