I'm currently studying JS, and in one of my projects, I want to create a fadeOut Navbar. I've played around with some code and I've found out that i need to know the number of pixels that the document is scrolled. But I've found only the answer for jQuery. I've found this code: $(document).scrollTop(); But I don't really know how to convert it in Vanilla JS. Could someone please help me or give me an advice of how to get the count of the pixels or same result scrolled in the document and store it in a variable? Thank you.
HTML
<head>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Roboto:wght@500&display=swap" rel="stylesheet">
</head>
<div class = "main-container">
<div class = "child-container-bg" >
<h3>Hello</h3>
</div>
</div>
CSS
body{
height: 4000px;
}
.main-container {
width: 100%;
height: 60px;
position: fixed;
top: 0;
z-index: 3;
color: #fff;
display: flex;
align-items: center;
justify-content: center;
}
.child-container-bg {
width: 100%;
height: 100%;
background: #000000;
opacity: 0;
font-family: 'Roboto', sans-serif;
text-align: center;
}
JS
window.addEventListener('scroll', (event) => {
let navBarFade = document.querySelector(".child-container-bg");
var fireHeader = function (noAnimate) {
let brkPoint = 400;
let fadeLength = 300;
let opacity;
const scrollTop = $(document).scrollTop(); //This is the part that I can't find to change in Javascript from jQuery. I've only found the jQuery version.
if (scrollTop < brkPoint) {
opacity = 0;
} else if (scrollTop > brkPoint + fadeLength) {
opacity = 1;
} else {
if (noAnimate) {
opacity = 1;
} else {
opacity = (scrollTop - brkPoint) / fadeLength;
}
}
navBarFade.style.opacity = opacity;
};
fireHeader(true);
window.addEventListener('scroll', fireHeader())
});
Without seeing what you have so far, something like this will work
let currentScroll = 0;
let navbarHeight = 40;
window.addEventListener('wheel', (event) => {
currentScroll = document.documentElement.scrollTop
if (currentScroll > navbarHeight) {
// logic to remove navbar
}
})