user3438917
user3438917

Reputation: 497

How to enable menu click when hiding div for responsive layout

I have a navigation that hides the sub-navigation menu .nav-sub-wrapper when resizing to tablet/mobile. The issue is that with this specific jQuery used to hide the menu on resize, it is disabling the menu from showing on mobile/tablet devices when clicking the menu (.hamburger) icon.

How can I enable the .hamburger menu to trigger the .nav-sub-wrapper class to display on click?

if($(window).width() <= '768'){
$(".nav-sub-wrapper, .desktop-search-box").hide();
$(".hamburger").on('click', function(){
  if($(".logo-link").css("display") == 'none'){
    $(".hamburger").addClass("hamburger-active");
  }
  $('.list-header').trigger('click');
  $(".nav-sub-wrapper").toggle();
  $(".search").show();
});
}

//used to hide nav on resize//
function navHidden() {
  if ($(window).width() <= 768) {
    $(".nav-sub-wrapper").hide();
    $(".hamburger").on('click', function() {
      $(".nav-sub-wrapper").toggle();
    });
    } else {
      $(".nav-sub-wrapper").show();
    }
  }

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

  $(document).ready(function() {
    navHidden();
  });

Upvotes: 0

Views: 153

Answers (1)

Sean Halls
Sean Halls

Reputation: 192

I think you will need to make sure you are unbinding the earlier hamburger "on" click event. When the page first loads at full screen, the click function is bound to the ".hamburger" element due to your first line of code.

if($(window).width() <= 768) {
   // Any event bindings you create here will still exist
   // even if you create a new binding somewhere else.
}

It doesn't matter if you resize to Desktop mode and this initial conditional (screen width <= 768) is no longer met, the click function defined here is still bound to the ".hamburger" element.

That means when you resize and click ".hamburger" in mobile mode, you are running both the mobile function and the earlier bound functions simultaneously. So you are toggling the nav twice, once on, once off. That is why you are having an issue.

Try this:

if ($(window).width() <= 768) {
    //Remove anything still bound from earlier that could be causing a double-fire.
    $(".hamburger").off('click');
    $(".hamburger").on('click', function() {
        $(".nav-sub-wrapper").toggle();
    });
}

Hope this helps,

Sean

P.S.:

Might want to refactor to something like this in the long run, which I think is a bit cleaner:

function isViewportMobile() {
 if($(window).width() <= 768) {
   return true;
  }
}

$(window).on("resize", function(){
   if (!isViewportMobile()) {
     useDesktopRules();
   } else {
     useMobileRules();
   }
});

Where useDesktopRules and useMobileRules would contain the jQuery/dom-manipulation code you provided earlier for each viewport.

Consider using a "throttling / debouncing" function as well, to prevent millions of function calls when the resize happens.

Upvotes: 1

Related Questions