I'm trying to make a div that cycles through background colors when hovered over with the mouse. I've figured out how to make the background color switch to a color value from a set of values on mouseenter
, but not how to make it keep going.
How do I make the background color keep changing while the mouse is hovered over the element (and stop once I've moused out)?
Here's a fully working fiddle of what I have so far: FIDDLE
My HTML:
<body>
<div id="coloredDiv" data-index="-1"></div>
</body>
My CSS:
#coloredDiv {
width:200px;
height:200px;
border:1px solid #888;
}
#coloredDiv:hover {
cursor:pointer;
}
My jQuery:
var colors = ['#eeeeee', "#00ff00", "#ff0000", "#000000"];
$(document).ready(function () {
$colorDiv = $('#coloredDiv');
ln = colors.length;
$('#coloredDiv').mouseenter( function () {
var i = $colorDiv.data("index");
++i;
if (i >= ln) i = 0;
$colorDiv.css({
'background-color': colors[i]
});
$colorDiv.data("index", i);
});
});
Use
Array.shift
andArray.push
to make cycle happenFiddle
For cycle to repeat on hover:-
Fiddle