views:

37

answers:

3

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
Is using a psuedo classes on a div valid?
Thomas
Definitely the time and place to use CSS. :)
Gert G
@Thomas - Yes, only older IE(6) has an issue, everyone else supports it IIRC. IE6 only supported the `:hover` pseudoclass on anchors.
Nick Craver
@Thomas - There's nothing wrong with that (I checked... it passed CSS validation).
Gert G
good to know - thanks!
Thomas
@Thomas - If it's important to support IE6, then you can add the hover effect with jQuery (see Darin Dimitrov's answer).
Gert G
@Gert - I've included this already...far better to do this with a class, much easier to maintain.
Nick Craver
+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
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
.support is preferable rather than browser sniffing http://api.jquery.com/jQuery.support/
redsquare