Search code examples
jquerymouseentermouseleave

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");
  });

Solution

  • 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");
        }
    })