I'm looking for a way to make my div disappear when I scroll down and reappear immediately when I start scrolling back up. Currently, it only works when I reach a certain position instead of taking effect right away. I need assistance in calculating the scroll position so that the effect happens instantly. Here is the code I have been working on:
window.addEventListener('scroll', function() {
if (window.scrollY < 5) {
document.getElementById('search-bar-scroll').classList.add('scrolled');
} else {
document.getElementById('search-bar-scroll').classList.remove('scrolled');
}
});
* {
margin: 0;
padding: 0;
}
img,
fieldset {
border: none;
}
body *,
*:after,
*:before {
box-sizing: border-box;
}
html,
body {
height: 250vh;
}
.main-wrapper {
max-width: 1400px;
margin-left: auto;
margin-right: auto;
}
.search-bar-scroll {
background: #1e5da5;
position: fixed;
height: auto;
width: 100%;
left: 0;
top: 0;
opacity: 0;
transition: 0.3s ease;
}
.scrolled {
opacity: 1;
transition: 150ms all;
}
<div class="search-bar-scroll" id="search-bar-scroll">
<fieldset class="home-header-search">
<div action="#" id="scroll-input-container">
<p>Hello World</p>
</div>
</fieldset>
</div>