Skip to content Skip to sidebar Skip to footer

Close Off-canvas Menu On Window Click

I made this 'slide-out' menu: SASS Slide-out Menu. It's ok, but I want that when the menu have slid, on window click the menu returns back(remove the class 'nav-open'). I tried thi

Solution 1:

You're close! I think your codepen example needs the close logic block tweaking to look like this:

  $(window).on("click", function(e) {
    if (
      wrapper.hasClass("nav-open") && 
      !$(e.target).parents(nav).hasClass("side-nav") && 
      !$(e.target).hasClass("toggle")
    ) {
        wrapper.removeClass("nav-open");
      }
  });

Some tips for you:

  1. Use $(window).on not window.on
  2. e.target is a DOM element, so you need to wrap it in jQuery like $(e.target)
  3. You can compare DOM elements, but not jQuery objects, so you can use hasClass instead
  4. I added a check to ignore a click on the toggle itself

Forked codepen with working code: http://codepen.io/anon/pen/mzAru

Post a Comment for "Close Off-canvas Menu On Window Click"