Julia Julia - 2 months ago 8
CSS Question

How to change color of element on hover and remove it when mouseout using jquery?

I found the following Snippet (color changes randomly on hover)
But there is now mouseout state – i want the link color to change in its original state when not hovering the link.

Can anyone help me with this?

$(document).ready(function() {
$( "p" ).mouseover(function() {
$(this).css("color",getRandomColor());
});

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


https://jsfiddle.net/99upf1jz/

Answer

The mouseleave event works exactly like the mouseover event. You can simply add it after the former, like this:

$( "p" ).mouseover(function() {
  $(this).css("color",getRandomColor());
}).mouseleave(function() {
    $(this).css("color", "black");
});

https://jsfiddle.net/McNetic/99upf1jz/2/

If you really want to restore the "original" color (regardless what it was), you have to save it first. That could be done with a data element to each attribute (a global variable like suggested by other answers will not restore each element to it's respective color):

$( "p" ).mouseover(function() {
  $(this).data("original-color", $(this).css("color")).css("color",getRandomColor());
}).mouseleave(function() {
    $(this).css("color", $(this).data("original-color"));
});

https://jsfiddle.net/McNetic/99upf1jz/5/