I am using Jquery - is there a simple way to change the background color on a div when a user rolls over it?
+2
A:
You can do this with CSS:
#myDiv:hover { background-color: red; }
//or...
div:hover { background-color: red; }
If you need IE6 support and such and have to use jQuery, toggle a class, like this:
.hover { background-color: red; }
Then use .hover()
and .toggleClass()
, like this:
$(".myDivs").hover(function() {
$(this).toggleClass('hover');
});
Nick Craver
2010-06-20 11:13:55
Is using a psuedo classes on a div valid?
Thomas
2010-06-20 11:15:25
Definitely the time and place to use CSS. :)
Gert G
2010-06-20 11:15:31
@Thomas - Yes, only older IE(6) has an issue, everyone else supports it IIRC. IE6 only supported the `:hover` pseudoclass on anchors.
Nick Craver
2010-06-20 11:16:12
@Thomas - There's nothing wrong with that (I checked... it passed CSS validation).
Gert G
2010-06-20 11:17:34
good to know - thanks!
Thomas
2010-06-20 11:18:14
@Thomas - If it's important to support IE6, then you can add the hover effect with jQuery (see Darin Dimitrov's answer).
Gert G
2010-06-20 11:24:10
@Gert - I've included this already...far better to do this with a class, much easier to maintain.
Nick Craver
2010-06-20 11:28:54
+1
A:
You could use the .hover() event:
$('#divid').hover(function() {
// mouse enter
$(this).css('background-color', 'red');
}, function() {
// mouse leave
$(this).css('background-color', 'blue');
});
Darin Dimitrov
2010-06-20 11:14:47
A:
I think mouseenter
& mouseleave
is better than hover. Why? Bubbling reason ;)
if($.browser.msie && $.browser.version < 7) {
$('element').bind({
mouseenter:function(){ $(this).addClass('over'); },
mouseleave:function(){ $(this).removeClass('over');}
});
}
After this, you can simply add some CSS magic:
#element.over,
#element:hover {
/* do something */
}
Ionut Staicu
2010-06-20 13:32:45
.support is preferable rather than browser sniffing http://api.jquery.com/jQuery.support/
redsquare
2010-06-20 15:26:03