I have 4 cards that contain images. When the image is in viewport I want the image to come from the left. I have finished all the css but when I run the JS, it always returns false even if the element is in viewport. I don’t need the whole image to be in the viewport at least half of it and I want it to return true. I have a for each loop that runs through all of the images but it always returns false.
This is the code that I have come up with:
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:
<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>
2
Answers
I made a simple example using your function in codepen, and it looks like your function is working as expected: https://codepen.io/lukenetsurfer/pen/WNPzQdO
The example includes a blue square that you can drag around the screen. If you open the console, you can see it print out the result of
isInViewport
each time you move the square. When the square is only partially visible (it’s hanging off the screen),isInViewport
returnsfalse
, otherwise it returnstrue
.A few debugging ideas to help you figure out why it’s not working on your end:
console.log
container
, does it have the value you expect? (Maybe you’re checking the wrong component?)console.log
the values in your boolean comparison, do those match your expectations?Use Intersection Observer as Darryl Noakes commented earlier.
I can’t really help you with specifics because the code posted in the question seems incomplete and the explanation is missing some critical details. The example below uses IO and details are in the comments.