Many websites are implementing animations when a element enters the viewport. Now this is a popular web design technique. In this post I will provide the easiest way to detect if element entered viewport or not.
Technique to detect element entering viewport
Here is the scenario for a div element we want to track.
Here we can calculate if the div is available in viewport or not by using a simple condition:
offsetTop > pageYOffset and offsetTop < innerHeight + pageYOffset
This is the code for tracking it
<html>
<head>
<title>Reveal On Scroll Animations</title>
<style>
.div1
{
height: 400px;
background-color: blue;
}
.div2
{
height: 220px;
background-color: green;
}
.div3
{
height: 1000px;
background-color: yellow;
}
.div4
{
height: 2000px;
background-color: grey;
}
</style>
</head>
<body>
<div class="div1" data-reveal="false"></div>
<div class="div2" data-reveal="true"></div>
<div class="div3" data-reveal="false"></div>
<div class="div4" data-reveal="true"></div>
</body>
<script>
function reveal()
{
var elements = document.querySelectorAll("[data-reveal][data-reveal='true']");
var length = elements.length;
for(var count = 0; count < length; count++)
{
/* offsetParent may not be the body if the element container is positioned. Therefore we need to find the distance from the body by adding all the offsetTop's of all offsetParent's. */
var offsetParentTop = 0;
var temp = elements[count];
do
{
if(!isNaN(temp.offsetTop))
{
offsetParentTop += temp.offsetTop;
}
}while(temp = temp.offsetParent)
var pageYOffset = window.pageYOffset;
var viewportHeight = window.innerHeight;
if(offsetParentTop > pageYOffset && offsetParentTop < pageYOffset + viewportHeight)
{
console.log(elements[count].className + " is visible");
}
}
}
/* Attach event handlers to resize and scroll event */
window.addEventListener("resize", reveal, false);
window.addEventListener("scroll", reveal, false);
</script>
</html>
scrollrevealjs for rescue
If you are too lazy to implement your own code for tracking it then you can use scrollrevealjs library.
Conclusion
In the above example we found viewport visibility for vertical alignment. You can use the same logic to write a code to detect horizontal alignment of a element in the viewport. For horizontal alignment you have to use offsetLeft, innerWidth and pageXOffset.