Quick Tip - Set Hover Class for Anything
Sometimes it's nice to be able to give users visual feedback when they hover their mouse over an element on the page. It's easy to do, of course, with a little CSS:
#hover-demo1 p:hover { background: #ff0; }
That little style rule changes the background of any paragraph that is a descendant of an element with id="hover-demo" to a nice bright yellow — but only when you hover your mouse over it. So, if that's all there is to it, what does this have to do with jQuery?
Unfortunately, (yep, you guessed it) Internet Explorer 6 and below don't support the :hover pseudo-class on any element except <a>. Bummer!
See for yourself here:
This is a paragraph. If you're using a modern browser, my background will be yellow when you hover over me.
Move your mouse over me! Move your mouse over me! I'll turn yellow, too! But not if you're using Internet Explorer 6 or below.
We could just leave it alone at this point and figure that people using real browsers will be rewarded with a little extra eye candy. On the other hand, maybe the right thing to do is to have mercy on the downtrodden. After all, even IE 6 users arguably have some aesthetic sense.
Enter jQuery
With a few lines of jQuery (one line, actually, if you don't care about making it readable) we can provide the hover effect to those using IE 6 or below, as long as they have JavaScript enabled. We also might as well keep the CSS rule in the stylesheet. Now, the only people who won't see the hover state change are those using Internet Explorer 6 (or below) with JavaScript off. Well, if they're using any browser with JavaScript and CSS turned off, they won't see it either. But that sort of folk ain't hankerin' for the eye candy anyway.
First, we give a simple class the same background as the aforementioned :hover pseudo-class:
.pretty-hover, #hover-demo1 p:hover {
background: #ff0;
}
Next, we use jQuery to add class="pretty-hover" to each paragraph when the user hovers over it:
-
}, function() {
-
});
Note: We switched to a different id here so that IE 6 users can see the difference between the two hover demos, but the idea is that you would use the .hover() method on the same elements that you applied the :hover pseudo-class to.
That's it! Give it a whirl:
This is a paragraph. My background will be yellow when you hover over me — even if you're using Internet Explorer.
Move your mouse over me! Move your mouse over me! I'll turn yellow, too! Internet Explorer users welcome!
Try it with Firefox, Safari, or Internet Explorer. Try it with any browser you wish (within reason) — and you should see the yellow.
Bonus!
If you'd like to replicate the look of a hovered link, you can add another CSS declaration to the "pretty-hover" class:
.pretty-hover {
background: #fee;
cursor: pointer;
}
That'll work nicely for showing and hiding effects triggered by clicking on elements other than <a>.



February 20th, 2007 at 5:27 pm
I am running Firefox 2.0.0.1 and neither box displays pink. Just displayed it in IE 7, there is a faint pink hue that I can see around the text if I lean in REAL close (I am 23 and have better than 20/20 vision with my contacts in...and they are in). Does not appear to be working in Opera 9.02 either.
February 20th, 2007 at 5:30 pm
Just to clarify, first statement should read "...and text in neither box displays pink."
February 20th, 2007 at 5:45 pm
Hi Matthew,
That is really odd. I just tried it in Firefox 2.0.0.1 (both Windows and Mac) and the paragraphs for both boxes showed the highlight color when I hovered over them. Same in Safari 2.x. In IE 6, as expected, no background color behind each paragraph in the first box, but in the second box it showed up just fine.
I just changed the background color to a bright yellow. Maybe the shade of pink was too subtle for your monitor. If you could refresh your browser and try again, that would be great.
February 21st, 2007 at 9:20 am
Isn't this one case where IE6 users can count themselves lucky - not to be troubled by awful paragraph hover effects?
February 21st, 2007 at 9:36 am
Ha! Yeah, I see what you mean, Chris. Surely, though, the principle can be put to much better (and less obnoxious) use than my example here — especially when attaching
onclickevents to elements other than <a>.February 21st, 2007 at 11:10 am
Perfect! Yellow shows up nice and clear in FF now...and IE 7...and IE 5.5 SP 2...and IE 6. (IE 5.5 and IE 6 only work on second box, as expected).
I guess it was just REALLY faint? Works like a charm now. Nice work and thanks for not taking my comments as harsh criticisms, just constructive inquiries
February 21st, 2007 at 12:57 pm
Yeah, I was only joking. I'm actually using something a bit like this on one of the sites I look after, to help IE6 with nested submenus.
I just really hate hover effects that have no particular purpose apart from drawing my attention to where I happen to have parked the mouse pointer.
February 21st, 2007 at 1:57 pm
@Matthew: Phew! So glad that it's working for you now. Yeah, I guess it was really faint. I was trying to use a color that wasn't so garish, but the lesson I've learned is that for demos and tutorials, garish might be the best option.
@Chris: You are a funny guy. I'm always entertained by your comments — so keep them coming!
February 22nd, 2007 at 8:44 am
Just testing...
Live Comment Preview is pretty cool!
February 22nd, 2007 at 11:13 am
very nice. succinct and to the point - I like it
March 4th, 2007 at 10:13 am
I think your tutorials are really nice. They help me out a lot with a project I'm working on
I especially liked those slide in slide out effects plus this hover tutorials would help me a a lot since I'm new to JQuery. Hope to see more tutorials for the less experienced like me!
March 20th, 2007 at 6:57 am
Yes ! they are really nice tutorials for me too !
please write more.. more... more... thanks !
March 20th, 2007 at 9:22 am
Zsa and laocung, I'm thrilled to hear that you are enjoying the tutorials. Thanks for your words of encouragement. If there is anything in particular that you would like to learn about, let me know.
March 21st, 2007 at 7:05 am
If you want to make a whole block clickable (if it has a link inside), you can make it look like a link like this. Note: the firstChild... line may need to be changed. I hope this helps someone.
$("li").click(function() {PS. I can't press enter in the comment box (FF 2.0 on WinXP)window.location = this.firstChild.firstChild.href;
});
$("li").hover(function() {
$(this).addClass("hoveredbg");
}, function() {
$(this).removeClass("hoveredbg");
});
March 21st, 2007 at 11:45 pm
Thanks for the tip, Dave. Haven't had a chance to test it, but it looks interesting. I suppose the
firstChild.firstChild.hrefpart will depend on the markup within theli.Perhaps something like this would work:
I have no idea what might be causing the problem with the enter key. I tested on FF2 on WinXP, and it worked fine.
June 21st, 2007 at 9:29 am
i'm looking to create a hover that changes one class to another (or just changes the background and border properties). the classes are actual boxes with heights and widths (with links inside). Basically, I'd like to be able to add a hover to the whole class instead of just the link text. Is this what Dave is talking about? If so can you possibly elaborate on how to do this?
July 11th, 2007 at 12:54 am
Just to clarify something about the ... pink discussion. You should specify your colours in full hexadecimal for modern browsers. Try putting the full hex in your style-sheet ie #ffff00 and it should work first time you can even put 'yellow' in the style-sheet!
July 11th, 2007 at 7:23 am
yannis, nobody had a problem seeing the yellow background (#ffff00). It was the pale pink that was causing the problem — not because it wasn't full hex, but because it was too pale. I always use shorthand (e.g. #ff0), and I live in modern browsers, but I've never had a problem with them. Is that what you're referring to, by the way? Full hex versus shorthand? If so, do you have a reference that I can look at (maybe from the W3C or something) that says to use full hex? This is news to me, so I'd like to read up on it.
July 12th, 2007 at 3:13 pm
karl, maybe I misunderstood the posts. My reference to colors being specified in full hex is to be able to specify a larger range of colors. From the W3C. The format of an RGB value in hexadecimal notation is a '#' immediately followed by either three or six hexadecimal characters. Both can be used in modern browsers, however it is preferable to use the full hex in order to capture tints and the like - what would short-hand be for #f9f9f9?. (The three digit notation gave us the web safe colours that we can now let to rest!).
October 9th, 2007 at 11:49 am
Remember those JavaScript snowflakes back in the day? It would be great to see a hover effect with snowflakes in a div. Or mousetrails.
Ok. Really I'm just kidding...
October 17th, 2007 at 6:18 pm
Has anyone tested this using background images? It is not working for me. The code below will change the font color and the pointer, but not the bg image.
October 17th, 2007 at 8:45 pm
Hi Marx,
Assuming that you are applying the "testhover" class directly to the element with an ID of "test," the problem is in the hierarchy of your CSS selectors. IDs get more weight than classes do. The color and cursor work because they haven't been defined as something else in the #test rule. If you have some kind of wrapper div with an id, you could put that in front of ".testhover" to make this work. So, you would define the class styles doing something like this:
December 20th, 2007 at 7:08 pm
how can I catch mouseout event on Item, when I scrolled the page with mouse wheel or keyboard, but I didn't move mouse? In this case the browser doesn't call onmouseout event
February 22nd, 2008 at 1:11 pm
Hi, I don't really know anything about jQuery and am having trouble implementing this even in a simple example. Any chance of a point in the right direction? This is what I have:
Am I completely missing the point here or have I overlooked something really obvious? Any help will be greatly appreciated. Thanks.
February 23rd, 2008 at 12:31 pm
Hi Turhan,
Since you're putting the script in the head of your document, it's trying to bind the hover function to the paragraph elements before they are registered in the DOM. So, effectively, it's attaching the function to nothing. You can avoid this problem by putting the script inside a window.onload, or better yet, inside jQuery's document.ready. Something like this:
For more information, please see Introducing $(document).ready().
February 24th, 2008 at 8:47 am
I am not sure if this works with background images. The div that this works on is a class.
February 24th, 2008 at 12:20 pm
D. Jones: You can't set a :hover pseudo-class through JavaScript, nor do you need to. Just make sure in your stylesheet that
.thumbnailbgcomes after.thumbnailbgex, and preferably that it have a greater level of specificity (for example, if.thumbnailbgexis defined with the bare class, put something like "body " in front of.thumbnailbg, like so:February 24th, 2008 at 3:42 pm
LOL. Ok I see what was doing wrong. I need to add another class in order for this to work. Doing that solved the problem.
March 4th, 2008 at 8:42 am
Hi Karl
Thanks for that info. I have tried using the code you provided (with the document.ready bit) and moved it to inside the body tag of the document. That didn't work either, so I assume I'm still putting the code in the wrong place... When should I be putting this? Thanks very much.
March 4th, 2008 at 9:59 am
Hi Turhan,
Do you have a URL that you can post here so that I can see what else might be going on with the code? That would be very helpful.
Make sure you're referencing the jquery core file in a script tag before the code for the hover stuff. For example:
And make sure that you have defined the ".pretty-hover" style in your stylesheet.
Hope that helps.
March 16th, 2008 at 2:53 pm
Great tutorial, love all the tutorials on the site. Just one question, is there a way to select every other div, or every even div. I know how to do it with tables,
ex $("table tr:nth-child(even)").addClass("toggle");
Tried
$("div.products div:nth-child(even)").addClass("toggle");
but for some reason won't work, any ideas
March 16th, 2008 at 2:58 pm
Hi Charles,
Thanks for the compliments.
The problem probably has to do with how those divs are nested. Are all of the divs within the same div.products? Or are they in separate ones? If you could point me to a page or show me an HTML snippet, I'll be able to help.
April 2nd, 2008 at 11:40 am
This tutorial was on point and I was able to successfully implement this after a bit of time. I'm not a programmer at all and I'm finding jQuery easier to handle with simple things like this. Thanks so much Karl.
April 24th, 2008 at 4:37 pm
awesome tutorial. this is exactly what I was looking for to ensure that each paragraph on my wordpress site gets highlighted when the mouse hovers over.
required adding the script tag to the header.php of my theme and thats it
June 27th, 2008 at 11:07 am
Great tutorial, thanks a lot.
I've used Java a lot, and found it to be fairly straight-forward. Javascript on the other hand.... Resources like your webpage have helped me create some pretty fun things that I wouldn't have bothered attempting otherwise.
Keep it up!
July 1st, 2008 at 8:32 pm
I thought hover would solve my problem but it doesn't seem to. I have an overlay that I want to display if I hover over the image. What happens is if I try anything other than hide/show the effect repeats.
Hover and slideUp gives me the overlay sliding up, sliding down, sliding up, and so on. This is what happened when using mouseover, mouseout and based on the description for hover would solve that.
my code
$('#widescreen_box').hover(
function () {
$('#overlay').slideUp('slow');
},
function () {
$('#overlay').slideDown('slow');
}
);
July 23rd, 2008 at 10:57 am
Phil, thank you! You saved a lot of my time. I had the same problem but didn`t manage to cope with it. Your solution works great!