Animate On Scroll Based On getBoundingClientRect API

Category: Animation , Javascript | March 7, 2023
AuthorkateFrontend
Last UpdateMarch 7, 2023
LicenseMIT
Views538 views
Animate On Scroll Based On getBoundingClientRect API

A super tiny animate on scroll library that uses getBoundingClientRect() to retrieve the position of an element relative to the viewport and then applies show/hide CSS classes to the element accordingly.

How to use it:

1. Add the following JavaScript snippets to your project.

const boxes = document.querySelectorAll('.box')
window.addEventListener('scroll', checkBoxes)
checkBoxes()
function checkBoxes() {
  // trigger point - where we want to start scrolling
  const triggerBottom = window.innerHeight / 5 * 4  
    boxes.forEach(box => {
      const boxTop = box.getBoundingClientRect().top
      if(boxTop < triggerBottom) {
        box.classList.add('show')
      } else {
        box.classList.remove('show')
      }
    })
}

2. Animate the element when it’s scrolled into view.

.box.show {
  transform: translateX(0);
}

You Might Be Interested In:


Leave a Reply