How to arbitrarily set color on hover

I have never seen the hover effect like before, and I'm trying to figure out how this is achieved. In this example, you will notice that when a user hovers over a link, the color by which the link occurs can be any one of the 5 colors that are assigned in the stylesheet (see below) in a random order. How do you create this guidance effect? Can this be done only with CSS?

a:hover { color:#1ace84; text-decoration: none; padding-bottom: 2px; border: 0; background-image: none; } a.green:hover { color: #1ace84; } a.purple:hover { color: #a262c0; } a.teal:hover { color: #4ac0aa; } a.violet:hover { color: #8c78ba; } a.pink:hover { color: #d529cd; } 
+6
source share
2 answers

Since a random factor has been introduced, I don't think there is a way to do this purely with CSS.

Here is my simple approach to the problem using jQuery.

Here you can see a working example: http://jsfiddle.net/GNgjZ/1/

 $(document).ready(function() { $("a").hover(function(e) { var randomClass = getRandomClass(); $(e.target).attr("class", randomClass); }); }); function getRandomClass() { //Store available css classes var classes = new Array("green", "purple", "teal", "violet", "pink"); //Get a random number from 0 to 4 var randomNumber = Math.floor(Math.random()*5); return classes[randomNumber]; } 
+9
source

The key part of jQuery code is loaded into the page footer.

Please pay attention to the authors' comment on the script or find the author's permission for reuse.

 /* Code below this point is not licensed for reuse, please look and learn but don't steal */ var lastUsed; function randomFrom(arr){ var randomIndex = Math.floor(Math.random() * arr.length); lastUsed = arr[randomIndex]; return lastUsed; } color_classes = ['green','purple','violet','teal','pink']; function initLinks() { $('#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 () { }); } 
+4
source

Source: https://habr.com/ru/post/910181/


All Articles