简体   繁体   中英

Close sidebar on new click (when menu link is clicked) for mobile?

What I want to have working: When screen size is under 992px, and a sidebar menu link is clicked, for the new page to open with no sidebar menu

Right now it works like this: When it's above 992px, it stays open and can be toggled open and closes. I have this code which works by closing the sidebar nav automatically when the screen size is under 992px and then you can toggle it open to view. Although, when you click a menu item it reopens on the new page open even when the screen is under 992px.

$(function(){
   $("#menu-toggle").click(function(e) {
       e.preventDefault();
       $("#wrapper").toggleClass("toggled");
   });

   $(window).resize(function(e) {
     if($(window).width()<=992){
       $("#wrapper").removeClass("toggled");
     }else{
       $("#wrapper").addClass("toggled");
     }
   });
});

When I click a menu item, it reopens the menu sidebar.

How can I have the code so where and when the menu item/link is click to open a new page, and then screen is 992px or less, it opens the new page with the menu toggled closed ?

As far as I can see, you should listen load event to. For example:

function checkWidthAndToggle() {
  if($(window).width()<=992){
    $("#wrapper").removeClass("toggled");
  }else{
    $("#wrapper").addClass("toggled");
  }
}

$(window).on('resize load', checkWidthAndToggle);

If you want to save space, you can write as follows. But I would not recommend)

$(window).on('resize load', ({ target: w }) => {
  $("#wrapper")[`${$(w).width() < 993 ? "remove" : "add"}Class`]("toggled")
});

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