Skip to content Skip to sidebar Skip to footer

How To Randomly Assign A Color On Hover Effect

I've never seen a hover effect like this before, and I'm trying to understand how it's achieved. You'll notice in this example, that when a user hovers over a link, the color the l

Solution 1:

Since a random factor is introduced, I don't think there's a way of doing it purely with CSS.

Here's my simple approach to the problem, using jQuery.

You can see a working example here: http://jsfiddle.net/GNgjZ/1/

$(document).ready(function()
{
    $("a").hover(function(e)
    {
        var randomClass = getRandomClass();
        $(e.target).attr("class", randomClass);
    });
});

functiongetRandomClass()
{
    //Store available css classesvar classes = newArray("green", "purple", "teal", "violet", "pink");

    //Get a random number from 0 to 4var randomNumber = Math.floor(Math.random()*5);

    return classes[randomNumber];
}

Solution 2:

The key piece of jQuery code is loaded in the footer of the page.

Please pay attention to the authors comment on the script, or seek the author's permission to reuse it.

/* 

  Code below this point is not licensed for reuse,
  please look and learn but don't steal

*/var lastUsed;
functionrandomFrom(arr){
  var randomIndex = Math.floor(Math.random() * arr.length);
  lastUsed = arr[randomIndex];
  return lastUsed;
}
color_classes = ['green','purple','violet','teal','pink'];
functioninitLinks() {
  $('#wrap a').hover(function() {
    new_classes = color_classes.slice();

    var index = $.inArray(lastUsed, new_classes);
    new_classes.splice(index, 1);

    var classes = $(this).attr('class');
    if (classes) {
        classes.split(' ');
        $(classes).each(function(i, className) {
            var index = $.inArray(className, new_classes);
            if (index>0) {
                new_classes.splice(index, 1);
            }

        });
    }
    $(this).removeClass(color_classes.join(' ')).addClass(randomFrom(new_classes));
  }, function () {
  });
}

Post a Comment for "How To Randomly Assign A Color On Hover Effect"