I make a mega-mega menu. I noticed that when I go from the main menu item to the last child on the diagonal, the block disappears. I decided to solve it by a delay of a second, half a second so that the user managed to point to the last item. How can I implement the delay? Now there is such a code

$('.mega-mnu ul li').hover(function () { var mega_inner = $(this).find('ul'); mega_inner.css({'display':'block'}); }, function () { $('.mega-mnu ul li i').remove(); var mega_inner = $(this).find('ul'); mega_inner.css({'display':'none'}).delay(5000); } ); 

http://codepen.io/jSas/pen/LbavKz

    2 answers 2

    To solve the problem, you need to analyze the direction of the mouse cursor movement: if the cursor moves vertically, then open menu items in normal mode, and if horizontally or diagonally, ignore the movement over adjacent menu items.

    Determining the direction of the cursor can be implemented as follows. Add the following snippet before your code:

     var prevPageX = 0; var isVerticalDirection = true; var directionTimer = 0; $('.mega-mnu ul').mousemove(function(e) { if (directionTimer) { return false; } directionTimer = setTimeout(function() { // в данном случае считается, что курсор движется не по вертикали, // если за время 50 миллисекунд его горизонтальное смещение больше 10 пикселей isVerticalDirection = Math.abs(e.pageX - prevPageX) < 10; clearTimeout(directionTimer); directionTimer = 0; prevPageX = e.pageX; }, 50); }); 

    And change your code like this:

     $('.mega-mnu ul li').hover(function () { if (isVerticalDirection) { $(this).css({'color':'#000'}); $(this).parent().find('li > ul:visible').hide(); var mega_inner = $(this).find('ul'); mega_inner.css({'display':'block'}); } }, function () { if (isVerticalDirection) { var mega_inner = $(this).find('ul'); mega_inner.css({'display':'none'}); } } ); 
       setTimeout(function(){ //some code here }, 1000) 
      • In my case, this does not work is obtained porridge. - JavAs