RJq RJq - 6 months ago 19
Javascript Question

jQuery add only one class on hover

I have a problem with adding only one class on hover without adding the others. Here is the problem:

HTML:

<ul id="ulnav">
<li><a><img src="images/nav/play.svg" class="animated" id="playnav"/></a></li>
<li><a><img src="images/nav/home.svg" class="animated" id="homenav"/></a></li>
<li><a><img src="images/nav/mountains.svg" class="animated" id="mountainsnav"/></a></li>
<li><a><img src="images/nav/contact.svg" class="animated" id="contactnav"/></a></li>
</ul>


I have a function:

var randomAnim = function(){
var result = Math.floor((Math.random()*9) +1);
switch(result) {
case 1:
result = "jello";
break;
case 2:
result = "wobble";
break;
case 3:
result = "tada";
break;
case 4:
result = "swing";
break;
case 5:
result = "shake";
break;
case 6:
result = "rubberBand";
break;
case 7:
result = "pulse";
break;
case 8:
result = "bounce";
break;
case 9:
result = "flip";
break;
}
return result; };


and im using it here:

$('#playnav').hover(function() {
var roll = randomAnim();
$('#playnav').addClass(roll);
$(this).on('webkitAnimationEnd mozAnimationEnd animationEnd', function() {
setTimeout(function(){
$('#playnav').removeClass(roll);
}, 2000);
});
});


Its basically adding random animation to #playnav.
The problem is that if I hover over the playnav element it will add multiple classes - e.g jello, wobble and pulse at the same time, which results in broken animation.

So my question is, how can I add only one class on hover?

Answer

I don't think you want to use .hover() I'd recommend .mouseenter() Single word swap for the fix.

$('#playnav').mouseenter(function() {...

This will only call your randomization function once, until the cursor leaves and then reenters the element. In fact, I'd lose the timer too.

$('#playnav').mouseenter(function() {
     var roll = randomAnim();
     $('#playnav').addClass(roll);
     $('#playnav').mouseleave(function() {
            $('#playnav').removeClass(roll);
     }); 
});

an alternative would be:

$('#playnav').mouseenter(function() {
         var roll = randomAnim();
         $('#playnav').addClass(roll);
    });
$('#playnav').mouseleave(function() {
         $('#playnav').attr('class', 'animated');
    }); 

and here is an updated jsfiddle with CSS library linked in. Nice effect. The library link = https://rawgit.com/daneden/animate.css/master/animate.css

And if you wanted to take it one step further, and animate each element independently, you could do this.

            $('.animated').mouseenter(function() {
                var roll = randomAnim();
                $(this).addClass(roll);
                $(this).mouseleave(function() {
                    $(this).removeClass(roll);
                });
            });