Search code examples
javascriptjquerydrop-down-menuslidetoggle

JQuery: issues with activating and disactivating a sliding menu


I am building a menu, it has sub menus that slides down when you hover over the parent item and stays down when you click an arrow next to the parent. I got the hovering part working but when i click the arrow and leave the 'active aria' of the parent it dosen't stay down.

The .click() function itself shoulden't be the problem because it changes the class and prints the log.

After some reading I thought that the .off() function would work but it dosen't seem to...

HTML

<ul id="menu-nav" class="main-navigation">
	<li class="menu-item">item 1</li>
	<li class="menu-item menu-item-has-children">Item 2
		<ul class="sub-menu">
			<li class="menu-item">Item 2.1</li>
			<li class="menu-item">Item 2.2</li>
		</ul>
		<span class="sub-menu-arrow">
			::after
		</span>
	</li>
	<li class="menu-item">Item 3</li>
	<li class="menu-item">Item 4</li>
</ul>

JQUERY

function menu_slide_toggle() {
  $('.sub-menu').slideToggle('fast');
}

$('.menu-item-has-children').hover( menu_slide_toggle );

$('.sub-menu-arrow').click(function(event) {
  $('.sub-menu-arrow').toggleClass('active');
  $('.sub-menu-arrow').toggleClass('inactive');

  if ($('.sub-menu-arrow').hasClass('active')) {
    console.log('active');
    $('body').off( 'hover', '.menu-item-has-children', menu_slide_toggle );
  } else {
    console.log('inactive');
    $('body').on( 'hover', '.menu-item-has-children', menu_slide_toggle );
  }
});

If you need any other code then this I'll be happy to post it to!


Solution

  • I found the reason it didn't work!

    you can't use the .off() or .on() functions with 'hover' you need to use 'mouseenter mouseleave' instead. And I changed the selector from the body to the item which has the hover applied.

    So the code that worked was:

    $('.menu-item-has-children').off('mouseenter mouseleave', menu_slide_toggle);