Quick Tip - Set Hover Class for Anything
read 48 commentsSometimes 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>.
48 comments
One Ping
-
[...] Otra solución, es utilizar el evento .hover y añadir o quitar una clase: $('ul.list-links a').hover(function() { $(this).addClass('class-hover'); }, function() { $(this).removeClass('class-hover'); }); [...]












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.
Just to clarify, first statement should read "...and text in neither box displays pink."
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.
Isn't this one case where IE6 users can count themselves lucky - not to be troubled by awful paragraph hover effects?
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>.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
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.
@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!
Just testing...
Live Comment Preview is pretty cool!
very nice. succinct and to the point - I like it
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!
Yes ! they are really nice tutorials for me too !
please write more.. more... more... thanks !
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.
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");
});
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.
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?
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!
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.
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!).
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...
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.
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:
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
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.
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().
I am not sure if this works with background images. The div that this works on is a class.
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: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.
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.
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.
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
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.
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.
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
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!
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');
}
);
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!
Hi there,
This is a great tutorial. But for some reason i can't get it to worl. I tested it with
Firebug and i can see the class="pretty-hover" is not added to the p element. So i guess it's the javascript. I read this tutorial for about 20 times. Did i miss something?
Here's my code:
Test
$('#hover-demo1 p').hover(function() {
$(this).addClass('pretty-hover');
}, function() {
$(this).removeClass('pretty-hover');
});
.pretty-hover, #hover-demo1 p:hover {
background: #ff0;
}
My car has four weels!
Thanks alot in advantage!
ehh that did not go as planned. Heres a link to my website.
Thanks!
Hi Jeronemo,
I think the only problem your script has is that it isn't wrapped in a document ready function. Try it this way instead:
See Introducing document ready for details.
Yeah, that's it! So that's why other jquery things didnt work either. Thanks alot ^^
I have one question remaining. I wondered if this works with a form button. I would like the form button to hover in IE. I tried to replace the p element by button but it doenst work?! I also tried to replace it by a class.. same result. Any idea?
I'm designing a site for a client's intranet and it works for every browser, except IE6 (with and without CDATA). Javascript is completely enabled for this site in IE, but the hover will just not work. Anyone have a tip?
Here's what I have in my head tag:
Hi Richard,
It's really, really hard to guess what the problem is without seeing the page. Could be a problem with CSS specificity, but who knows? Can you provide a link?
thanks.
Hi Karl,
Unfortunately no, it's on an intranet site. It's driving me nuts, as it works in every browser that I've tried, except IE6; Chrome, FF 2&3, Opera, etc, all work as expected. I think I'm going to try some other, non-hover javascript stuff to see if it works, and if I figure it out, I'll post it here.
Hi all,
I am having some problem with HOVER event. It doesn't work correctly. Here is the code:
JS:
$j('.big_button').hover(
function() {
$(this).addClass("big_button_hover");
},
function() {
$(this).removeClass("big_button_hover");
}
);
CSS:
.big_button {
border-top:solid 1px #ddd;
border-left:solid 1px #ddd;
font-size:1.125em;
color:#444;
background-color:#CCCCCC;
cursor:pointer;
font-weight:bold;
height:30px;
overflow:visible;
border-right:solid 1px #999999;
border-bottom:solid 1px #999999;
text-shadow:#719e03 1px 1px;
padding-left:5px;
padding-right:5px;
width:auto;
}
.big_button_hover {
border-top:solid 1px #999999;
border-left:solid 1px #999999;
border-right:solid 1px #999999;
border-bottom:solid 1px #999999;
font-size:1.125em;
color:#fff;
background-color:#CCCCCC;
cursor:pointer;
font-weight:bold;
height:30px;
overflow:visible;
text-shadow:#719e03 1px 1px;
padding-left:5px;
padding-right:5px;
width:auto;
}
HTML:
Could anyone help me to solve out this problem?
Many thanks
Richard and Vietnam...,
Please take a look at the demo page I put up here: http://test.kswedberg/hover.html
It has both of your examples, and they're both working fine in IE6. Also, you should both test your scripts using Firefox with the Firebug extension (and enable the Console) to see if your page is reporting any JavaScript errors.
Richard, the problem could be elsewhere -- maybe with a JavaScript error or something. I'd recommend removing
.menu li:hoverfrom the style rule and see if it still works in other browsers. As it is, the other browsers could be styling those li elements purely with CSS.Vietnam..., one possible issue I see is that you're using
$j()in one place and$()in the others. Something to look into.this is awesome, great job, thx