I made my navbar to stick to the top only when I scroll down. But again when I scroll up then it instantly gets to the bottom(it's previous position). I want my navbar to stick to the previous position when it's showing in the window. Here is my code-
HTML:
<section >
<img src="./Assets/Asset [email protected]" width="320" alt="Brand Icon">
<p >Luxury Jewelry Store</p>
<nav >
<a href="#" >Home</a>
<a href="#" >My Cart</a>
<a href="#" >My Orders</a>
<a href="#" >FAQs</a>
<a href="#" >About Us</a>
<div >
<i ></i>
<input placeholder="Search..." type="search">
<input type="submit" value="Search" >
</div>
</nav>
</section>
CSS:
.section-1{
height: 100vh;
width: 100%;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
position: relative;
}
.navbar{
display: flex;
justify-content: center;
align-items: center;
width: 100%;
height: 50px;
background-color: #92A9BD;
position: absolute;
bottom: 0;
transition: all 0.3s;
z-index: 1;
}
.sticky{
position: fixed;
top: 0;
left: 0;
right: 0;
}
JS:
window.onscroll = function() {
const navbar = document.querySelector(".navbar");
if (window.pageYOffset > navbar.offsetTop) {
navbar.classList.add("sticky");
} else {
navbar.classList.remove("sticky");
}
};
CodePudding user response:
you just need to change the position from fixed to sticky
.sticky{position : sticky;
top:0;
left:0}
no need to mess with right;
CodePudding user response:
As @harsh-deep and @Zeikman suggested, I removed the JS code and just used sticky as position-
.sticky {
position: sticky;
top: 0;
}
and in html file I added sticky to the nav element. It was really simple! Thank You!