EN
JavaScript - change navbar style on scroll bottom event
0
points
In this article, we would like to show you how to change navbar style on scroll event using JavaScript.
Quick solution:
var navbar = document.querySelector('.element'); // gets element by class
window.onscroll = function() {
if (document.body.scrollTop >= 20 || document.documentElement.scrollTop >= 20 ) {
navbar.classList.add('blue'); // adds "blue" class when page is scrolled 20px down
}
else {
navbar.classList.remove('blue'); // removes class when page is scrolled back to top
}
};
Practical example
In this example, we present how to change the navbar element color when we scroll the web page 20px to the bottom.
// ONLINE-RUNNER:browser;
<!doctype html>
<html>
<head>
<style>
.container {
height: 500px;
}
.navbar {
width: 100%;
height: 20px;
position: sticky;
top: 0;
background: lightblue;
transition: 0.5s;
}
.blue {
background: blue;
}
</style>
</head>
<body style="height: 100px">
<div class="container">
<div class="navbar"></div>
</div>
<script>
var navbar = document.querySelector('.navbar');
function updateStyle() {
if (document.body.scrollTop >= 20 || document.documentElement.scrollTop >= 20 ) {
navbar.classList.add('blue');
}
else {
navbar.classList.remove('blue');
}
}
document.addEventListener('scroll', updateStyle);
</script>
</body>
</html>
Explanation:
- We use
addEventListenerto addscrollevent to the window element, so theupdateStyle()function will be called every time we scroll the web page, - every time the
updateStyle()function is called, it checks the distance from the top (scrollTopproperty), if it is more than20pxit adds theblueclass to thenavbarelement or removes it if it's less than20px, position: stickywithtop: 0makes thenavbaralways visible at the top of the web page,transition: 0.5smakes smooth color change effect.
Note:
In the solution we use both
document.bodyanddocument.documentElement:if (document.body.scrollTop >= 20 || document.documentElement.scrollTop >= 20 )because of the browsers compatibility, to make sure it always works.