This happens to be my 1st inquiry.
Specifically, I have a navigation menu with a transparent background and I am attempting to alter the background once it reaches the top edge of the window.
window.addEventListener("scroll", navSticky);
function navSticky(){
let nav = document.getElementById('navbar');
let bounding = nav.getBoundingClientRect();
if(bounding.top <= 0 ){
nav.classList.add("sticky");
}else{
nav.classList.remove("sticky");
}
}
*{
margin: 0;
text-align: center;
}
body{
background: lightgrey;
}
header h1{
padding: 40px;
}
nav{
position: sticky;
top: 0;
padding: 12px;
background: linear-gradient(to right,
rgba(0,0,0,0),
rgba(0,255,0, 0.5),
rgba(255,0,0, 0.5),
rgba(0,0,0,0));
color: black;
}
nav:before{
content: "now bg transparent";
}
.container{
min-height: 1000px;
padding: 20px;
}
nav.sticky{
background: linear-gradient(to right,
rgb(0,255,0),
rgb(255,0,0));
color: white;
}
nav.sticky:before{
content: "now bg isn't transparent";
}
<body>
<header>
<h1>Header, that request you scroll page</h1>
</header>
<nav id="navbar">
</nav>
<div class ="container">
While scrolling the page and when the nav hits the top of the screen, .sticky is added to classList<br>
</div>
</body>
It's functioning as intended, but I do have some inquiries:
- Can this be achieved without JavaScript?
- Is there a way to optimize this script since the scroll event is triggered frequently?
Appreciate your help!