Problem

  • During frontend development, there are animations that are triggered based on the position of the screen when scrolling
  • Some examples can be fade in, infinite scroll, …

Solution

  window.addEventListener('scroll', function() {
    const element = document.querySelector('#selector')
    const { scrollTop, clientHeight, scrollHeight } = element
    const { top, bottom } = element.getBoundingClientRect()
    
    const viewportHeight = window.innerHeight

    // Checking whether fully visible
    if(top >= 0 && bottom <= viewportHeight) {
      console.log('Fully visible')
    }

    // Checking for partial visibility
    if(top < viewportHeight && bottom >= 0) {
      console.log('Partially visible')
    }
    
    // Check if scrolled to bottom
    if (scrollTop + clientHeight >= scrollHeight) {
        console.log('Bottom')
    }
    
  })