I’m working on a website where I want to enable an element to fade in when i scroll down to a certain point. I’ve tried implementing this using vanilla HTML, CSS, and JavaScript, but the element is not triggering the animation on scroll as expected. I’ve followed various tutorials and suggestions, but I’m still facing difficulties. Could you please help me troubleshoot and provide guidance on how to make a fade-in animation trigger on scroll?
Used code:
<html>
<head>
</head>
<body>
<h1 class="anim">hi</h1>
</body>
<script>
const obj = document.getElementById("anim")
$(window).scroll(function() {
var height = $(window).scrollTop();
if(height > 100) {
$(obj).addClass("fade");
}else{
$(obj).addClass("fade");
}
});
</script>
</html>
2
Answers
There are few issues in your code :
I thinks with these changes your code will work fine.
When the page is scrolled, the script calculates the distance of the element from the top of the viewport. If the element is within 100 pixels from the bottom of the viewport, the "fade" class is added, making the element gradually appear with opacity transition.