0

On large screens, I want dropdowns to appear on hover, but on mobile I want to arrange them like accordions.

My jQuery is conflicting with my CSS. On mobile, clicking the li creates all kinds of problems: the event fires over and over, and if I resize to larger viewport, the dropdown remains open and the :focus and :hover rules are disabled.

Sass

// If bigger screen, show the submenu on hover or focus
ul.sub {
  display: none;
}

body.desktop {
  li.dropdown:hover,
  li.dropdown:focus {
    > ul.sub {
      dispay: block;
    }
  }
}

JavaScript

  if ($('body.desktop').length < 1) {
    $('li.dropdown > a').on('click', function(e){
      $(this).parent().find('.dropdown-menu').slideToggle('fast');
      e.preventDefault();
    });    
  } else {
    return false;
  }
brogrammer
  • 804
  • 1
  • 12
  • 22

1 Answers1

0

The problem was the style="display:none;" rule applied by the .slideToggle() method. I needed to devise a way to override this on larger viewports.

JavaScript

  $(window).resize(function(){
    if (window.innerWidth > 795 ) {
      $('.dropdown-menu').removeAttr('style');
    }
  });

Then, to stop the event from firing again and again, hat-tip to this solution:

$("li.dropdown").unbind().click(function() { ... });
Community
  • 1
  • 1
brogrammer
  • 804
  • 1
  • 12
  • 22