JSFiddle - React, Tailwind, and code Playground

by Thet Hlaing

HTML

<div id="firstDiv">

</div>

<div id="secondDiv">
  <span>Title is here</span>
</div>

CSS

div{
  height:100vh;
  width:100%;
  background-color:Blue;
  border-bottom:2px solid black;
}

span{
  font-size:30px;
  transform:translateY(200px);
  transition:transform 1s ease;
}

div.animated span{
  transform:translateY(0px);
}

JavaScript

function isElementInViewport (el) {

    //special bonus for those using jQuery
    if (typeof jQuery === "function" && el instanceof jQuery) {
        el = el[0];
    }

    var rect = el.getBoundingClientRect();
    console.log(rect);    
    return (
        rect.top >= 0 &&
        rect.left >= 0 &&
        rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) && /*or $(window).height() */
        rect.right <= (window.innerWidth || document.documentElement.clientWidth) /*or $(window).width() */
    );
}


document.addEventListener("scroll",function(){
	const secondDiv = document.querySelector("#secondDiv");
  if(isElementInViewport(secondDiv)){
  	  console.log("in the viewport");
  		secondDiv.classList.add('animated');
  }
  else{
      console.log("not in the viewport");
  		secondDiv.classList.remove('animated');
  }
});