DEV Community

Haruka Kakiuchi
Haruka Kakiuchi

Posted on • Edited on

IntersectionObserver

This memo from 'The Complete JavaScript Course 2024: From Zero to Expert!' on Udemy.

const header = document.querySelector('.header');
const navHeight = nav.getBoundingClientRect().height;


const stickyNav = function (entries) {
  const [entry] = entries; // entries[0]

  if (!entry.isIntersecting) nav.classList.add('sticky');
  else nav.classList.remove('sticky');
};

const headerObserver = new IntersectionObserver(stickyNav, {
  root: null,
  threshold: 0,
  rootMargin: `-${navHeight}px`,
});
headerObserver.observe(header);
Enter fullscreen mode Exit fullscreen mode

Bad way(The performance of the app on mobile devices is affected by the firing of an event on every scroll.)

const initialCoords = section1.getBoundingClientRect()

window.addEventListener('scroll', function(e) {
  console.log(window.scrollY);
  if(window.scrollY > initialCoords.top) nav.classList.add('sticky');
  else nav.classList.remove('sticky')

})

const obsCallback = function (entries, observer) {
  entries.forEach(entry => {
    console.log(entry);
  });
};

const obsOptions = {
  root: null,
  threshold: [0, 0.2], // [0, 1, 0.2] (100%)
};
Enter fullscreen mode Exit fullscreen mode

Scroll revealing

const allSections = document.querySelectorAll('.section')

const revealSection = function(entries, observer) {
  const [entry] = entries;

  if(!entry.isIntersecting) return; // Guard

  entry.target.classList.remove('section--hidden')
  observer.unobserve(entry.target) // for paformance
}

const sectionObserver = new IntersectionObserver(revealSection, {
  root: null,
  threshold: 0.15,
})

allSections.forEach(function(section) {
  sectionObserver.observe(section)
  section.classList.add('section--hidden') // for everyone can see the section including person who block JS
})
Enter fullscreen mode Exit fullscreen mode

Top comments (0)