Menu mouseenter mouseleave click

Can anybody help me? I want a pop-up menu with animation on mouseenter and mouseleave events, but when I click after mouse input, I want the submenu to remain visible until a new click is anywhere on the page (in the example, only in the body). After this second click (the same mouseleave animation), I want the mouseenter and mouseleave to repeat again when we started.

$('#menu > li').on('mouseenter',function(){ //mouseenter handler }); $('#menu > li').on('mouseleave',function(){ //mouseleave handler }); $('#menu > li').toggle( function () { $('#menu > li').off('mouseenter mouseleave'); }, function () { //mouseleave handler }); $('body').click(function(){ //same mouseleave handler }); 

I do not know how I can enable mouseenter / mouseleave after the second click. Sorry and thank you.

+2
source share
1 answer

This can be greatly simplified by event delegation:

 $('document').on("click",'#menu > li', function() { $('#menu > li').off('mouseenter mouseleave'); }); $('document').on("click",':not(#menu > li)', function() { $('#menu > li').on('mouseenter', function(){ //your mouseenter handler goes here }); $('#menu > li').on('mouseleave', function(){ //your mouseleave handler goes here }); }); 

This is semantically equivalent:

 If a click happens on a menu item, unbind mouse enter/leave events If a click happens on a non menu item, bind mouse enter/leave events 
+1
source

All Articles