简体   繁体   中英

How to hide menu for mobiles by default? Using Javascript

I have a website with side-bar menu. Menu is by default visible. If i click close-btn. Menu is hidden. That works

I would like make menu by default visible for desktops and by default hidden for mobiles.

.side-bar {
  background: #1b1a1b;
  backdrop-filter: blur(15px);
  width: 250px;
  height: 100vh;
  position: fixed;
  top: 0;
  z-index: 50;
  left: 0px;
  overflow-y: auto;
  transition: 0.6s ease;
  transition-property: left;
}
.side-bar.non-active {
  left: -250px;
}

.side-bar.active {
  left: 0px;
}

The window.innerWidth < 850 works but i'm not sure if there is something better. 850px i use for @media queries.

$(document).ready(function () {
  //jquery for toggle sub menus
  $(".sub-btn").click(function () {
    $(this).next(".sub-menu").slideToggle();
    $(this).find(".dropdown").toggleClass("rotate");
  });

  //jquery for expand and collapse the sidebar

  if (window.innerWidth > 850) {
    $(".close-btn").click(function () {
      $(".side-bar").addClass("non-active");
      $(".menu-btn").css("visibility", "visible");
    });

    $(".menu-btn").click(function () {
      $(".side-bar").removeClass("non-active");
      $(".menu-btn").css("visibility", "hidden");
    });
  } 
else {
    $(".side-bar").css("left", -250);
    $(".close-btn").click(function () {
      $(".side-bar").addClass("active");
      $(".menu-btn").css("visibility", "visible");
    });
    $(".menu-btn").click(function () {
      $(".side-bar").removeClass("active");
      $(".menu-btn").css("visibility", "hidden");
    });
  }
});

The issue is propably in $(".side-bar").css("left", -250); because in the DOM i can see it as inline style and after click nothing happen. Only .menu-btn disappers.

Is there another way how to set "reverse" logic for mobiles please? Or maybe just easy fix this i hope little bug?

I tried set oposite style for left: -250px; to left:0; via following logic but without any positiv result..

Use this instead:

if (window.matchMedia('(max-width: 850)').matches) { ... }
else { ... }

This uses css media query in JavaScript without any frameworks.

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