Skip to content
Advertisement

Howto: add class when section is in viewport

I am trying to get a drawing animation effect similar to https://stackoverflow.com/a/45378478 (Preview: https://codepen.io/jbanegas/pen/LjpXom) 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.

jQuery

<script type='text/javascript'> 
    $(document).ready(function(){
        $('.thisisatest').addClass('draw');
    });
</script>

HTML

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

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

onloadhttps://www.w3schools.com/jsref/event_onload.asp

.scroll()https://api.jquery.com/scroll/

Any help would be greatly appreciated.

Advertisement

Answer

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 (
    distance.top >= 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
      element.classList.add("draw");
    }
});
}, false);

EXAMPLE: jsfiddle

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