简体   繁体   中英

Responsive Mobile Menu

I have a function that applies a class to the html element and also detects if a drop down has been clicked below the width of 900px.

When I resize the browser from desktop view to below 900px I find occasionally that the dropdown class "active-hit" doesn't get applied - meaning that the menu won't open. Any ideas why this might be? I have to reload the page to make it work in mobile view.

// Add Mobile View Class to HTML ELEMENT below 900px
(function($) {
var $window = $(window),
    $html = $('html');
    $dropdown = $('.dropdown-nav > a');

function resize() {
    if ($window.width() < 900) {

      $dropdown.on('click', function(e){
        $(this).parent().toggleClass('active-hit');
        e.preventDefault();
        e.stopPropagation();
      });

      return $html.addClass('mobile-view');

    } else {
      $html.removeClass('mobile-view');
      $dropdown.parent().removeClass('active-hit');
    }

}
$window
    .resize(resize)
    .trigger('resize');
})(jQuery);

As I mentioned in a comment, window resize will not trigger your function, but if You want to do so in testing purposes then you can try to use this:

$(window).resize(function() {
  resize();
});

And here is working fiddle for you

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM