Interaction Observer

Draft Disclaimer: Please note that this article is currently in draft form and may undergo revisions before final publication. The content, including information, opinions, and recommendations, is subject to change and may not represent the final version. We appreciate your understanding and patience as we work to refine and improve the quality of this article. Your feedback is valuable in shaping the final release.

Language Mismatch Disclaimer: Please be aware that the language of this article may not match the language settings of your browser or device.
Do you want to read articles in English instead ?

Interaction Observer

Intro

Use case

  • lazy load image
  • cool css transition when element appear or disappear
    • TODO: GIF from website about and resume
    • fade in when showing for the first time
  const ratio = .1
  const options = {
  root: null,
  rootMargin: '0px',
  threshold: ratio
  }
  
  const handleIntersect = (entries, observer) => {
    entries.forEach(entry => {
      if (entry.intersectionRatio > ratio) {
        // $element is visible
        entry.target.classList.add('.visible')
        observer.unobserve(entry.target)
        // compare with method above observer.disconnect()
      }
    })
  }
  
  const observer = new IntersectionObserver(handleIntersect, options)
  const $elements = document.querySelectorAll('.appear')
  $elements.forEach($element => {
    observer.observe($element)
  })

Note: if javascript is disabled

Be cautious though because if javascript is disabled on the browser the end user won't see the expected behavior

Solution: Use a wrapping css class for before applying your custom behavior

function onLoaded () {
  document.documentElement.classList.add('.appear-enabled')
}
// Method A:
window.addEventListener('load', onLoaded)

// Method B:
if (document.readyState === 'complete') {
  onLoaded()
} else {
  document.addEventListener('DOMContentLoaded', onLoaded)
}
.appear-enabled .appear {

}
/* instead of */
.appear {
  
}

I personally prefer Method B

Wrap up

You can see what we could take from Web API new feature (not so new) InteractionObserver without any heavy computing (window scroll)