tags:

views:

1517

answers:

4

I have an element that can have an arbitrary background colour (set via a CMS).

I want to highlight it by brightening it on mouse over and darkening it on mouse out.

I tried using .css('background-color') to get and set the value but it seemed to be a lot more fiddly than I expected.

What's the non-dumb way to do this?

Edit: Just to clarify - the fiddly bit is parsing and doing arithmetic with colour values - not coping with the events.

Edit: The colour plugin gave me a way to read colour values but without colour arithmetic and writing support I still had to do some donkey work.

In the end I went with a fast 'fadeTo' but need to confirm that opacity animation works properly in IE6.

A: 

Use the jQuery hover event.

var overColor  = "#ddd";
var outColor = "#ccc";

$('#target').hover(function()
{
  $(this).css("background-color", overColor);
},
function()
{
  $(this).css("background-color", outColor);
});

To deal with getting the existing colour and then changing it, you'll have to find a library that can understand modify HTML #XXXXXX-style colours. You'll also have to be careful of if someone set the background color to a name like "red".

cdmckay
+3  A: 

Have you checked out the jQuery Color plugin?

I think color operations do not exists in the core jQuery code but maybe recent versions of jQuery may have already included it.

You need it to make jQuery understand color operations properly.

chakrit
This looks like a good example of a library that can handle HTML colours.
cdmckay
U still need the color plugin with 1.3.2
redsquare
A: 

I don't know what you mean by "fiddly" but I just tested this and it seems to work on the latest jQuery

$(document).ready(function() {
    var originalbc = $("#ThingThatChangesColors").css("background-color");
    $("#ThingThatChangesColors").mouseenter(function() {
        $(this).css("background-color", "#FFF");
    });
    $("#ThingThatChangesColors").mouseleave(function() {
        $(this).css("background-color", originalbc);
    });
});
Jason Punyon
It's the fact that I don't know what colors to set - I just want to get the current color and modify it.
andybak
Now I understand.
Jason Punyon
+1  A: 

If you want smooth color changes on hover, you can try the jquery-glow plugin

mishac