I am attempting to make an image on a website fade in and up when a user scrolls the image into the viewport. The code I have so far is below. However, when I run this code I get a 404 error output. Any assistance is appreciated! I am quite new to JS and have been trying to figure this out for a while.
Here is my CSS.
.section3 {
opacity: 0;
transform: translateY(20vh);
visibility: hidden;
transition: opacity 0.6s ease-out, transform 1.2s ease-out;
will-change: opacity, visibility;
}
.fade {
opacity: 1;
transform: none;
visibility: visible;
}
Below is the HTML and JS.
<section id="section3" class="section3">
<img style="width: 100%;" src="lovethyneighbor.jpg">
</section>
<script>
var section3 = document.getElementById("section3");
var location = section3.getBoundingClientRect();
if (location.top >= 0) {
document.getElementById("section3").classList.add("fade");
} else {
document.getElementById("section3").classList.add("section3");
}
</script>
Introducing the Intersection Observer API! This is included in JavaScript and is a great tool for triggering an event/function when an element is in the viewport.
It's a really powerful tool and I'd highly suggest using this over
getBoundingClientRect(). One of the main reasons for this is with your code:You will have to run a function on every single mousewheel event, which is unreliable and can hurt performance. If you're using Intersection Observer, the API will "watch" your page and will run a function whenever the element is in the viewport. The code below is explained through inline comments.
Scalable with multiple elements that need different animations
Simple function with single element and single animation