Skip to content

Instantly share code, notes, and snippets.

@vxhviet
Last active July 25, 2023 12:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vxhviet/605fdd7c05a561dee5b77af99b7576b8 to your computer and use it in GitHub Desktop.
Save vxhviet/605fdd7c05a561dee5b77af99b7576b8 to your computer and use it in GitHub Desktop.

[JavaScript] - Revealing Elements on Scroll - Intersection Observer API

SOURCE

<section class="section" id="section--1">
// ...
</section>

<section class="section" id="section--2">
// ...
</section>

<section class="section" id="section--3">
// ...
</section>
.section--hidden {
  opacity: 0;
  transform: translateY(8rem);
}
const allSections = document.querySelectorAll('.section');

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

  if (!entry.isIntersecting) return;

  entry.target.classList.remove('section--hidden');
  observer.unobserve(entry.target);
};

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

allSections.forEach(function (section) {
  sectionObserver.observe(section);
  section.classList.add('section--hidden');
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment