kaluk
kaluk

Reputation: 53

Short code mouseenter & mouseleave

Write working code, but it's big. How to reduce this code:

$('.js_service').mouseenter(function() {
    $(this).find('span').addClass("js_animated fadeOutLeft");
  })
  .mouseleave(function() {
    $(this).find('span').removeClass("fadeOutLeft").addClass("fadeInLeft");
  })
  .mouseenter(function() {
    $(this).find('span').removeClass("fadeInLeft").addClass("fadeOutLeft");
  });

Upvotes: 0

Views: 112

Answers (3)

charlietfl
charlietfl

Reputation: 171679

You could roll this all up into one hover() handler .

$('.js_service').hover(function() {
   $(this).find('span').toggleClass("js_animated fadeOutLeft fadeInLeft") 
});

When only one argument provided it will fire for both mousenter and mouseleave and toggleClass will handle add/remove class.

If you provide 2 handlers as arguments then the first is mouseenter and the second is mouseleave

$(selector).hover(function(){
  /* mousenter code */
},function(){
  /* mosueleave code*/
});

Reference: hover() API docs

Upvotes: 2

Bill
Bill

Reputation: 3517

You can use the hover function to have either one function that fires on both events, or two functions. Here is the documentation page

$('.js_service').hover(function() {
   $(this).find('span').addClass("js_animated").toggleClass("fadeOutLeft fadeInLeft");
});

This code will make sure you have the js_animated class and will toggle the fadeOutLeft and fadeInLeft. Make sure your spans have one of the classes to begin with otherwise they will both toggle on and off at the same time. In your case I think you want to have the fadeInLeft class on them.

Upvotes: 0

Merry Christmas
Merry Christmas

Reputation: 26

You don't need two mouseenter handlers:

$('.js_service').mouseenter(function() {
    $(this).find('span').addClass("js_animated fadeOutLeft")
                        .removeClass("fadeInLeft");
    })
    .mouseleave(function() {
        $(this).find('span').removeClass("fadeOutLeft").addClass("fadeInLeft");
    })

And you can actually roll it into a single handler if you bind it using hover:

$('.js_service').hover(function(e) {
    if (e.type === "mouseenter") {
        $(this).find('span').addClass("js_animated fadeOutLeft")
                            .removeClass("fadeInLeft");
    } else {
        $(this).find('span').removeClass("fadeOutLeft").addClass("fadeInLeft");
    }
})

Upvotes: 1

Related Questions