Just want to generate a random number and then add it as a class to an existing div.
But can’t get the variable to be recognised by addClass.
JS
$(function() {
$("#button_text").mouseenter(function() {
var randomNum = Math.Round(Math.random()*3);
$("#buttons").addClass(randomNum);
}).mouseleave(function() {
$("#buttons").removeClass(randomNum)
});
});
HTML
<div id="buttons">
</div>
Any help much appreciated.
Thanks for all the help.
Final solution was…
JS
$(function() {
$("#button_text").mouseenter(function() {
randomNum = 'rand' + Math.round(Math.random()*2);
$("#buttons").addClass(randomNum);
}).mouseleave(function() {
$("#buttons").removeClass(randomNum)
});
});
HTML
<div id="buttons">
</div>
<p>Insert intro sentence here.</p>
<div id="button_text">
<p>Insert text here that will display the random button background when moused over</p>
</div>
CSS
#button_text
{
display: block;
}
#buttons
{
width: 200px;
height: 200px;
display: block;
position: absolute;
top: 145px;
left: 370px;
z-index: -999;
}
#buttons.rand0
{
background: url(/hover_buttons.png) no-repeat;
background-position: 0 0;
}
#buttons.rand1
{
background: url(/hover_buttons.png) no-repeat;
background-position: 0 -230px;
}
#buttons.rand2
{
background: url(/hover_buttons.png) no-repeat;
background-position: 0 -440px;
}
There’s a scoping issue in play here. Make sure your random reference is accessible by both methods. Below I’m declaring my variable outside of my methods, changing its value from the
$.mouseenter()method and then accessing it again from the$.mouseleave()method.In my example I’m merely setting the text of an element, and then incrementing the text. You can adapt this to your needs by changing the two calls to
$.text()to$.addClass()and$.removeClass()respectively.Note also that it’s not advised to use numbers as class names. Perhaps you should prefix the values.
Online Demo: http://jsbin.com/icuwav/edit