stormec56 stormec56 - 4 months ago 29
CSS Question

Random Hover Effects

How can you randomize hover effects?

For example:

<p>test</p>

p:hover {
background: yellow;
}

p:hover:
background: red;
}


Please note that the above is for-example only. The question is, how can you randomize hover effects, so it shows the
background:yellow;
and
background:red;
once in random order on the
onmouseover
?

There should not be any order, like for example: on first hover - one class is added, on second - another. It should be completely random.

Answer

Use the following function to get random colors and use mouseover event to change the background color.

function getRandomColor () {
 var letters = '0123456789ABCDEF'.split('');
 var color = '#';
 for (var i = 0; i < 6; i++) {
     color += letters[Math.floor(Math.random() * 16)];
 }
 return color;
    }
})

$( "p" ).mouseover(function() {
$(this).css("background",getRandomColor());
});

Please check this Fiddle.