I have a fixed side navigation menu that has a height of 100%. When you click the hamburger in the corner its width gets set to 15%-100% depending on your window's size. And when you click the x its width is set to 0. The percentage is set relative to the body. This seemed to be working great until I added content so that I could scroll. When you scroll down and then open/close the side nav it brings you back to the top of the page.
I'm not very familiar with JavaScript so it is possible there is a problem in there. I searched Google and StackOverflow but I didn't find anything. It's possible I might not be searching for the right problem. I tried changing all of the percentages to vh and vw and that changed nothing. I also don't believe it is a browser problem (I use Chrome) because I tried it in Microsoft Edge as well and that produced the same results.
<body onresize="WindowResize()">
<!--side-menu-->
<nav class="navbar">
<span class="open-Slide">
<a href="#" onclick="openSlideMenu()">
<span id="hamburger" class="icon-menu"></span> /*an Icon font I have downloaded*/
</a>
</span>
<div id="side-menu">
<a href="#" class="btn-close" onclick="closeSlideMenu()">×</a>
<a href="#">Home</a>
<a href="#">Portfolio</a>
<a href="#">Blog</a>
</div>
</nav>
<!--end of side-menu-->
//side-menu script
var sideMenuWidth;
var sideMenuIsActive = true;
window.onload = function() {
if (window.innerWidth > 1143) {
sideMenuWidth = '15%';
}else{
sideMenuWidth = '100%';
}
}
function openSlideMenu () {
document.getElementById('side-menu').style.width = sideMenuWidth;
sideMenuIsActive = true;
}
function windowResize() {
if (window.innerWidth > 1143) {
sideMenuWidth = '15%';
if (sideMenuIsActive == true) {
document.getElementById('side-menu').style.width = sideMenuWidth;
}
}else{
sideMenuWidth = '100%';
if (sideMenuIsActive == true) {
document.getElementById('side-menu').style.width = sideMenuWidth;
}
}
}
function closeSlideMenu() {
document.getElementById('side-menu').style.width = '0';
sideMenuIsActive = false;
}
//end of side-menu script
#side-menu {
width:15%;
z-index: 1;
transition: 0.5s;
top:0;
left:0;
background-color: black;
height: 100%;
position: fixed;
}
#hamburger {
display: absolute;
top: 0;
left:0;
margin: 1rem 0 0 1rem;
position: fixed;
color: black;
}
Any help is greatly appreciated!
You need to prevent default behaviour for link with attr href="#" or remove href https://www.w3schools.com/jsref/event_preventdefault.asp
If you need interactive element, but don't need href
attribute use <button>
element instead and apply needed CSS for this element. This is better option from accessibility concern.
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.