DEV Community

Cover image for How To Know If An Element Is Visible In Viewport.

How To Know If An Element Is Visible In Viewport.

Lucius Emmanuel Emmaccen on February 16, 2021

In this article, we're going to learn how to know/detect if an element is visible in the browser's viewport. Before we start, I'd like to clarify ...
Collapse
 
orkhanjafarovr profile image
Orkhan Jafarov • Edited

Nice! It’s awesome that IntersectionObserver was added in JS and does it easily .

Collapse
 
emmaccen profile image
Lucius Emmanuel Emmaccen

Thanks, Orkhan. The IntersectionObserver really is a considerable option.

Thanks again for bringing that up 🥂.

Collapse
 
maciekgrzybek profile image
Maciek Grzybek

Intersection Observer is a total game-changer for me :) I wrote a tutorial on how you can use it in real life -> dev.to/maciekgrzybek/create-sectio...

BTW, nice article Lucius :)

Thread Thread
 
emmaccen profile image
Lucius Emmanuel Emmaccen

Thanks, Maciek.
I just looked it up and bookmarked. Nice article. 💯%

Thread Thread
 
maciekgrzybek profile image
Maciek Grzybek

Thanks :)

Collapse
 
andrewbridge profile image
Andrew Bridge

I've found getBoundingClientRect can become an expensive call if it's used a lot. The scroll event is fired very rapidly in some browsers too, so as with most things involving this event, it's usually worthwhile debouncing calls to your handler.

Of course if you're able to use the InteractionObserver as others have suggested then great! But your method provides a much wider browser compatibility!

Collapse
 
emmaccen profile image
Lucius Emmanuel Emmaccen • Edited

Good feedback, Andrew.
By the looks of it, I should probably update the article. Everyone needs to know the cost of using getBoundingClientRect and how InteractionObserver might be a better fit in heavier projects.
By teaching, I've learnt a lot myself, thanks for pointing this out.

Collapse
 
devdahcoder profile image
Adigun Olamide

Well explained..

Collapse
 
emmaccen profile image
Lucius Emmanuel Emmaccen

Thanks.

Collapse
 
emmaccen profile image
Lucius Emmanuel Emmaccen

Thanks for sharing, Daniel.

Collapse
 
karimimahdi profile image
karimimahdi

What if the elements height is greater than viewport height???????
what is the algorithm????