Search code examples
jquerymouseentermouseleavejquery-hover

jQuery hover, mouseenter, mouseleave state (opacity animate)


I am trying to understand them but seems like I cannot. So I thought if someone can help me to better understand how these works.

When I add hover state it simply do opacity effect whether mouse is on the element or when mouse leaves element... It repeats it...

And mouseenter&leave works fine but I don't know how to tell him once $(this) so I made something and it works but perhaps someone may tell me what is correct and better way.

$("nav.topMenu-left li, nav.topMenu-right li").on('mouseenter', function() {
    $(this).animate({'opacity': '0.5'}, 100);
});

$("nav.topMenu-left li, nav.topMenu-right li").on('mouseleave', function() {
    $(this).animate({'opacity': '1'}, 100);
});

Solution

  • You can combine your event handlers:

    $("nav.topMenu-left li, nav.topMenu-right li").on('mouseenter mouseleave', function(e) {
       if (e.type === 'mouseenter')
          $(this).animate({'opacity': '0.5'}, 100);
       else 
          $(this).animate({'opacity': '1'}, 100);   
    });
    

    Or as you are not delegating the events you can use hover method:

    $("nav.topMenu-left li, nav.topMenu-right li").hover(function(){
        $(this).animate({'opacity': '0.5'}, 100);
    }, function(){
        $(this).animate({'opacity': '1'}, 100);   
    })