If you saw the awful title and still wanted to help answer this, thank you so much.
I got inspired by this website marussiabeverages.com to try manipulating some CSS based on scroll position. Just like the site, I want to fade a fixed background out as the user scrolls down.
I've attached an example of what I have right now: The opacity set to zero and increasing as more of .hero
is scrolled through, causing a fade in effect. Basically, I want to reverse it so the opacity starts at 1 and is reduced as the page is scrolled.
This feels like there's an obvious answer I'm missing, but I'm not great with logic. Thanks again!
Bonus: I noticed the browser doesn't calculate every pixel if you scroll too fast. It's not terribly important for what I'm doing here, but if you know how to address this, please let me know.
document.addEventListener("DOMContentLoaded", function() {
function fade() {
const BG_HERO = document.querySelector(".bg-hero");
const HERO = document.querySelector(".hero");
const DEMO = document.querySelector(".demo");
let height = HERO.offsetHeight;
let position = document.documentElement.scrollTop;
let o = position / height;
let opacity = o.toFixed(2);
if (position <= height) {
BG_HERO.style.opacity = opacity;
DEMO.innerHTML =
`
Position / Height: ${position} / ${height}
<br>
Opacity: ${BG_HERO.style.opacity}
`;
}
}
document.addEventListener("scroll", function() {
fade();
});
});
.hero {
height: 600px;
}
.bg-hero {
position: fixed;
top: 0;
right: 0;
bottom: 0;
left: 0;
background: url(https://picsum.photos/1920/1080) bottom center no-repeat;
background-size: cover;
opacity: 0;
}
.demo {
position: fixed;
top: 50%; left: 50%;
transform: translate(-50%,-50%);
background: #000;
color: #fff;
}
<div class="bg-hero"></div>
<div class="hero">Scroll Me!</div>
<div style="height: 999px;">
<p class="demo"><p>