'Prevent scroll bar to go up when click mobile nav
I have a mobile nav and I open it using this code in JS file:
var toggleButton = document.querySelector(".toggle-button");
var mobileNav = document.querySelector(".mobile-nav");
var closeButton = document.querySelector(".close-button");
toggleButton.addEventListener("click", function () {
mobileNav.classList.add("slide");
});
closeButton.addEventListener("click", function () {
mobileNav.classList.remove("slide");
});
.mobile-nav {
position: fixed;
transition: 0.4s ease;
transform: translateX(1400px);
}
.slide {
transform: translateX(0);
}
when I scroll down and open mobile nav using slide class the scroll bar goes up, how to fix it? i want it to remain at current place where I open slide menu.
here is project Github page for more codes: enter link description here
and here is the online website for reprodure the issue, just make browser page smaller than 768px and scroll down then tap hamburger icon to see the issue.
Solution 1:[1]
const navSection = document.querySelector(".nav-section");
function openNav() {
navSection.classList.add("open-nav")
}
function closeNav() {
navSection.classList.remove("open-nav")
}
.nav-section{
width: 100%;
height: 100%;
position: fixed;
top: 0;
left: 0;
opacity: 0;
transition: 0.25s;
pointer-events: none;
}
.nav-section nav{
display: flex;
flex-direction: column;
position: relative;
transform: translateX(-100%);
width: 20rem;
height: 100%;
background: red;
}
.open-nav{
pointer-events: all;
opacity: 1;
background: rgba(0, 0, 0, 0.5);
}
.open-nav nav{
transform: translateX(0%);
}
.close-nav-btn{
position: absolute;
right: 0;
top: 0;
}
<div class="open-btn">
<button onclick="openNav()">open</button>
</div>
<section class="nav-section">
<nav>
<a>nav 0</a>
<a>nav 1</a>
<a>nav 2</a>
<a>nav 3</a>
</nav>
<button onclick="closeNav()" class="close-nav-btn">close</button>
</section>
Like this maybe?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Mutex |
