Happylab Logo
Published on

Day13: Slide in on Scroll

Authors
js30

Project Introduction: Create an animation effect where images slide into view when scrolling to specific points.

Project Page: https://iris1114.github.io/javascript30/13_Slide-in-on-Scroll/

Code

// Can only trigger once within 20 seconds
function debounce(func, wait = 20, immediate = true) {
  var timeout
  return function () {
    var context = this,
      args = arguments
    var later = function () {
      timeout = null
      if (!immediate) func.apply(context, args)
    }
    var callNow = immediate && !timeout
    clearTimeout(timeout)
    timeout = setTimeout(later, wait)
    if (callNow) func.apply(context, args)
  }
}

// When page scrolls to specified height, make images slide in/out of article
function checkSlide() {
  sliderImages.forEach((sliderImage) => {
    // Page scroll distance + screen height - half image height = height for image to slide in
    const slideInAt =
      window.scrollY + window.innerHeight - sliderImage.height / 2

    // Image distance to screen top + image height = distance from image bottom to screen top
    const imageBottom = sliderImage.offsetTop + sliderImage.height

    // Check if reached slide-in height: slide-in height > image distance to screen top
    const isHalfShown = slideInAt > sliderImage.offsetTop

    // Check if not reached slide-out height: page scroll distance < distance from image bottom to screen top
    const isNotScrolledPast = window.scrollY < imageBottom

    // If reached slide-in height and not reached slide-out height, add 'active' style
    if (isHalfShown && isNotScrolledPast) {
      sliderImage.classList.add('active')
    } else {
      sliderImage.classList.remove('active')
    }
  })
}

const sliderImages = document.querySelectorAll('.slide-in')

window.addEventListener('scroll', debounce(checkSlide))

Additional Notes

Window.scrollY

Number of pixels that the document is currently scrolled vertically.

Window.innerHeight

Height of the browser window's viewport in pixels, including the height of the horizontal scroll bar if present.

HTMLElement.offsetTop

Read-only property that returns the distance of the current element's top border to the top inner border of its offsetParent element.

References

https://blog.epoch.tw/ https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/offsetTop