Animate On Scroll Based On getBoundingClientRect API

Category: Animation , Javascript | March 7, 2023
Author:kateFrontend
Views Total:353 views
Official Page:Go to website
Last Update:March 7, 2023
License:MIT

Preview:

Animate On Scroll Based On getBoundingClientRect API

Description:

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