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];
}
There seem to have two problems in your code:
addClass() function that does exactly what you wantSo 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];
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With