I am working on a project that involves 4 cards with images. I want the image to animate in from the left when it comes into viewport. I have finalized the CSS for this effect, but the JavaScript code always returns false even when the element is visible on the screen. I specifically want the function to return true when at least half of the image is in the viewport. Despite using a forEach loop to check all images, the function keeps returning false.
Below is the JavaScript code snippet I have developed:
function isInViewport(container) {
const rect = container.getBoundingClientRect();
return (
rect.top >= 0 &&
rect.left >= 0 &&
rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) &&
rect.right <= (window.innerWidth || document.documentElement.clientWidth)
);
}
This is the HTML structure I am using:
<div class="col-md-6 col-sm-12 p-0 overflow-hidden bg-dark imageCard">
<div class="imageCont">
<img
src="images/ferrariPhoto1.webp"
alt=""
style="width: 100%; height: 100%"
class="ferrariImageSection"
/>
</div>
</div>