DEV Community

Michał Górnicki
Michał Górnicki

Posted on

Objects animation when visible in window viewport

I used to hard-code proper height for javascript function to animate object with property window.pageYOffset. It mostly worked well but sometimes created problems, for example with viewing page on mobile phones.
Better way to solve this problem is to use getBoundingClientRect() - this method returns the size of an element and its position relative to the viewport. So if you write getBoundingClientRect().top you will get distance in pixels from bottom of viewport to top of selected object.

Example of use of this method:
if (document.getElementById("container").getBoundingClientRect().top < 0) {
document.getElementById("container").style.backgroundColor="black"}
else {document.getElementById("container").style.backgroundColor="white"}

In this case if top of "container" will touch beginning of our viewport background color of this object will turn to black.
Feel free to use my code.

Top comments (0)