Skip to content

Howto: add class when section is in viewport

I am trying to get a drawing animation effect similar to (Preview: to load when the user scrolls to this section of the page. It’s intended to add multiple of these drawing boxes as the user navigates the page.

I realize that jQuery is sort of outdated now, but this is on a WordPress website that already utilizes this framework.


<script type='text/javascript'> 


<div class="thisisatest"></div>

I’ve tried replacing the .ready() with:



Any help would be greatly appreciated.



You are missing the basics. Apart from adding on scroll event you need to find out if element is in view port obviously.

Here is vanilla JS solution…

It will work on all div’s with content and .thisisatest class.

References Read the link on how the isInViewport function work.

var isInViewport = function(elem) {
  var distance = elem.getBoundingClientRect();
  return ( >= 0 &&
    distance.left >= 0 &&
    distance.bottom <= (window.innerHeight || document.documentElement.clientHeight) &&
    distance.right <= (window.innerWidth || document.documentElement.clientWidth)
// read the link on how above code works

var findMe = document.querySelectorAll('.thisisatest');

window.addEventListener('scroll', function(event) {
// add event on scroll
findMe.forEach(element => {
    //for each .thisisatest
    if (isInViewport(element)) {
      //if in Viewport
}, false);

EXAMPLE: jsfiddle

User contributions licensed under: CC BY-SA
3 People found this is helpful