0

I have this code to add a class from a list when the mouse is over a button, and it works, but every time the mouse touches the button a new class is added from the list. I need it just add one class.

var classes = ["fadeOutRight","fadeOutLeft","fadeOutDown","fadeOutUp","zoomOutLeft","zoomOutRight","zoomOutDown","zoomOutUp"];

$(".work").mouseover(function() {
    $(".paj").each(function(){
        $(this).addClass(classes[~~(Math.random()*classes.length)]);
    });
});

I tried this but is not working:

var classes = ["fadeOutRight","fadeOutLeft","fadeOutDown","fadeOutUp","zoomOutLeft","zoomOutRight","zoomOutDown","zoomOutUp"];

$(".work").mouseover(function() {
  if(!$(this).hasClass(classes)){
    $(".paj").each(function(){
        $(this).addClass(classes[~~(Math.random()*classes.length)]);
        });
    };
});

Also, I need when the mouse is out it deletes all classes from the list. I tried this but it does not work either:

$(".work").mouseout(function() {
    $(".paj").removeClass(classes);
});
MCA
  • 1
  • 1

2 Answers2

0

try this solution may be helpful

 var classes = ["fadeOutRight","fadeOutLeft","fadeOutDown","fadeOutUp","zoomOutLeft","zoomOutRight","zoomOutDown","zoomOutUp"];


var checkclass = false;
$(".work").mouseover(function() {
    if(checkclass==false) {
       $(".paj").each(function(){
         $(this).addClass(classes[~~(Math.random()*classes.length)]);
       });
    } else {
        checkclass=true;
    }
});
danish farhaj
  • 1,316
  • 10
  • 20
0

This is because you are using addClass

You may use other methods to change the class (given that your element does not have any other class), as explained here.

Your code could then be:

var classes = ["fadeOutRight","fadeOutLeft","fadeOutDown","fadeOutUp","zoomOutLeft","zoomOutRight","zoomOutDown","zoomOutUp"];

$( ".work" ).mouseover( function() {
    $( ".paj" ).each( function(){
        $( this ).attr( 'class', classes[~~(Math.random()*classes.length)] );
    });
});
Community
  • 1
  • 1
Cyrille Armanger
  • 649
  • 5
  • 18