Search code examples
jquerymobiletouch

Toggle class on mouseleave or touchend


I'm trying to get a jQuery dropdown menu to work on both mobile and desktop (touch and non-touch devices).

Everything is working as expected, but I'm having trouble getting the 'selected' class to toggle on/off. Also, if you have any advice for making this more performant please let me know.

$(function(){

  $('li.nav__main__item--has-children > a').on('click',function(event){

    event.preventDefault();

    $(this).toggleClass('selected');

    $(this).parent().find('ul').first().toggle(300);

    $(this).parent().siblings().find('ul').hide(200);

    //Hide menu when clicked outside
    $(this).parent().find('ul').on('mouseleave touchend',(function(){ 
      var thisUI = $(this);

      $('html').click(function(){
        thisUI.hide();
        $('html').unbind('click');
      });
    }));

  });
});

Here's a Codepen with the full example: https://codepen.io/friendlywp/pen/WXpXWv

Thanks for your help.


Solution

  • $(function(){

    $('li.dropdown > a').on('click',function(event){

    event.preventDefault();
    $(this).toggleClass('selected');
    $(this).parent().find('ul').first().toggle(300);
    
    $(this).parent().siblings().find('ul').hide(200);
    
    //Hide menu when clicked outside
    $(this).parent().find('ul').parent().mouseleave(function(){ 
      var thisUI = $(this);
      $('html').click(function(){
        thisUI.children(".dropdown-menu").hide();
    thisUI.children("a").removeClass('selected');
    
        $('html').unbind('click');
      });
    });
    

    });

    });

    https://codepen.io/piscu/pen/EbWQda