jQuery Random Link Color Animations

Written by David Walsh on Tuesday, December 9, 2008


We all know that we can set a link’s :hover color, but what if we want to add a bit more dynamism and flair? jQuery allows you to not only animate to a specified color, but also allows you to animate to a random color.

The jQuery Javascript

$(document).ready(function() {
	original = $('a.random-color').css('color');
	$('a.random-color').hover(function() { //mouseover
		var col = 'rgb(' + (Math.floor(Math.random() * 256)) + ',' + (Math.floor(Math.random() * 256)) + ',' + (Math.floor(Math.random() * 256)) + ')';
		$(this).animate({
			'color': col,
			'paddingLeft': '20px'
		},1000);
	},function() { //mouseout
		$(this).animate({
			'color': original,
			'paddingLeft': '0'
		},500);
	});
});

For the color animation portion, you’ll need an extra Color Animations jQuery plugin. The padding nudge is another neat effect. This effect isn’t for everyone, but it can add another subtle effect to your jQuery-enabled website.


Follow via RSS Epic Discussion

Commenter Avatar December 09 / #

Nicely done David! But I think you should do 256 since – i believe – (Math.floor(Math.random() * 255)) will never return 255, just 0- 254.

Commenter Avatar December 09 / #
James says:

Nice idea David!

The animation is a little slow though…

Commenter Avatar December 09 / #

Cool idea. I think that there should be some constraints on the colours though as sometimes the link turned off-white.

var col = ‘rgb(‘ + (Math.floor(Math.random() * 51)) + ‘,’ + (Math.floor(Math.random() * 51)) + ‘,’ + (Math.floor(Math.random() * 153)) + 51′)’;

for example will always (I think) be a colour between #000033 and #3333CC

David Walsh December 09 / #
david says:

@Benjamin Sterling: Good point. Updated.

@James: Speed can be adjusted, so no worries there.

@Clinton Montague: This is a great consideration and one I looked at when developing. I decided to leave it out because it’s a “per site” issue.

Commenter Avatar December 14 / #

Hi David.

Its is simply superb.

Commenter Avatar May 08 / #
John Smith says:

Great effect David! Thanks for sharing it with us.

Does anyone know of a way to make this compatible with IE 7 by chance?

David Walsh May 09 / #

@John Smith: Works for me!

Commenter Avatar May 10 / #
John Smith says:

Cheers David – figured out my issue – I just had a conflicting css definition that I somehow glazed over.

Commenter Avatar November 17 / #
tuft says:

hi, just suggestion: call stop() on element before starting new animation:

$(this).stop().animate({ …

it will eliminate dancing menu item after multiple mouseover/mouseout…

Be Heard!

I want to hear what you have to say! Share your comments and questions below.

Name*:
Email*:
Website:  


© David Walsh 2007-2010. Contact David Walsh. Powered by the remarkable MooTools javascript framework.