Created
June 9, 2024 15:26
-
-
Save Ding-Fan/d7eabccc8718f212ab15ae0e60c1e0fa to your computer and use it in GitHub Desktop.
make bottom opaque when scroll down
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const overlay = document.querySelector(".overlay"); | |
let lastScrollTop = 0; | |
// console.log("I'm in.") | |
// Apply initial styles | |
overlay.style.transition = "opacity 0.5s ease"; | |
overlay.style.opacity = "1"; | |
window.addEventListener("scroll", () => { | |
let scrollTop = window.pageYOffset || document.documentElement.scrollTop; | |
if (scrollTop > lastScrollTop) { | |
// Scrolling down | |
overlay.style.opacity = "0.1"; | |
} else { | |
// Scrolling up | |
overlay.style.opacity = "1"; | |
} | |
// Check if the page is scrolled to the top | |
if (scrollTop === 0) { | |
overlay.style.opacity = "1"; | |
} | |
lastScrollTop = scrollTop <= 0 ? 0 : scrollTop; // For Mobile or negative scrolling | |
}); | |
// Change opacity when hovering | |
overlay.addEventListener("mouseover", () => { | |
overlay.style.opacity = "1"; | |
}); | |
overlay.addEventListener("mouseout", () => { | |
if (window.pageYOffset > 0) { | |
overlay.style.opacity = "0.1"; | |
} | |
}); | |
// Ensure opacity is 1 when the page can't scroll up anymore | |
const checkScrollEnd = () => { | |
if (window.innerHeight + window.scrollY >= document.body.offsetHeight) { | |
overlay.style.opacity = "1"; | |
} | |
}; | |
window.addEventListener("scroll", checkScrollEnd); | |
window.addEventListener("resize", checkScrollEnd); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment