MotoTony
MotoTony

Reputation: 61

jQuery hover each different background color

How to hover every different background-color? These code set the background-color is working:

var dlcabgColors = [
    'rgb(233, 147, 26)', 'rgb(22, 145, 190)', 'rgb(22, 107, 162)' , 'rgb(27, 54, 71)'
];

var i = 0;
$('.abc').each(function() {
    $(this).css('background-color', dlcabgColors[i]);
    i = (i + 1) % dlcabgColors.length;
});

But when I add hover function,the function will repeat all background-color.

I want to specify the elements of a specified color, not repeat all background color

The Fiddle

As always, your assistance is appreciated!

Thanks!every one:)

Upvotes: 4

Views: 531

Answers (2)

Roko C. Buljan
Roko C. Buljan

Reputation: 206342

Is this what you want?
LIVE DEMO Depending on the index 0f the hovered one change the color to match the array position:

var dlC = [
    'rgb(233, 147, 26)',
    'rgb(22, 145, 190)',
    'rgb(22, 107, 162)',
    'rgb(27, 54, 71)'
];
var dlH= [
    '#000',                    /* only difference... why that? */
    'rgb(22, 145, 190)',
    'rgb(22, 107, 162)',
    'rgb(27, 54, 71)'
];

$('.abc').each(function( i ) {
   $(this).css({backgroundColor : dlC[i] })
          .on("mouseenter mouseleave",function( e ) {
              $(this).css({backgroundColor : e.type=="mouseenter" ? dlH[i] : dlC[i] });
          });
});

the ? : I used is a Ternary Operator. You can Goog for it if you don't know how the logic works.

Upvotes: 3

fmsf
fmsf

Reputation: 37167

You should do that with CSS only, the only thing you need to is create proper classes for it and then add them to your elements. i.e.:

var totalColors = 4;

$('.abc').each(function(i, e) {
    $(this).addClass("color"+i%totalColors);
});

.color1:hover { background: #0FF }
.color2:hover { background: #FF0 }
.color3:hover { background: #0F0 }
.color0:hover { background: #F00 }

Edit: minor fix and here is a fiddle: http://jsfiddle.net/CxmGp/

Edit2: you can also generate the css classes directly through javascript: How to dynamically create CSS class in JavaScript and apply?

Upvotes: 3

Related Questions