Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript to randomize padding-bottom

Newbie here to javascript. I tried to follow the link here : How to randomly assign a color on hover effect

but I failed to replicate the same effect on my #menu_4645908 nav link...

I use #menu_4645908.red:hover but to no effect.

Note: I did change the variables of the classes from colour to padding , i just used the same class name while i work, will change when its working..

any idea where i went wrong?

[UPDATE]

This is the css im using, copied from the thread,

#menu_4645908.green:hover { color: #1ace84; }
#menu_4645908.purple:hover { color: #a262c0; }
#menu_4645908.teal:hover { color: #4ac0aa; }
#menu_4645908.violet:hover { color: #8c78ba; }
#menu_4645908.pink:hover { color: #d529cd; }

And this is the javascript

$(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"); 

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

   return classes[randomNumber]; 
} 
like image 670
Da Hao Avatar asked Jun 01 '26 14:06

Da Hao


1 Answers

There seem to have two problems in your code:

  1. jQuery has an addClass() function that does exactly what you want
  2. The class should not be assigned on hover, but rather at the loading of page

So try this instead: (JsFiddle)

$(document).ready(function() {
  $.each($("a"), function(index, element){
    $(this).addClass(getRandomClass());
  });
});

function getRandomClass() { 
 //Store available css classes 
 var classes = new Array("green", "purple", "teal", "violet", "pink");
 //Give a random number from 0 to 5
 var randomNumber = Math.floor(Math.random()*6); 
 return classes[randomNumber]; 
}

EDIT: as user Semicolon said in the comments, this only works if you only wanted the random classes to be assigned at pageload.

In that case, you could just assign a specific color each time:

$(document).ready(function() {
  ("a").hover(function(){
    $(this).css('color', getRandomColor());
  }, function(){
    $(this).css('color', ''); // Reverts to default color
  });
}); 

function getRandomColor() {
 var colors = new Array("#1ace84", "#a262c0", "#4ac0aa", "#8c78ba", "#d529cd");
 var randomNumber = Math.floor(Math.random()*colors.length); 
 return colors[randomNumber];
} ​
like image 75
Christophe Marois Avatar answered Jun 04 '26 02:06

Christophe Marois