Random Link-Color on Hover Mouseout Event

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;
    }
})

I’m sure there’s a better way, but at least this gets the desired result:

$(document).ready(function() {

var origColor = $("p").css("color");

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

$( "p" ).mouseout(function() {
$(this).css("color", origColor);
});

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

The ideal would be to remove the style attribute altogether.

I think you could just do this:

$(document).ready(function() {
$( "p" ).hover(function() {
	$(this).css("color",getRandomColor());
	}, function() {
    $(this).css("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;
    }
})

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.