🪴 yshalsager's Digital Garden

Search

Search IconIcon to open search

JavaScript Intersection Observer API

Last updated Jun 29, 2022

المعرفة:: JavaScript
الحالة:: #ملاحظة_مؤرشفة
المراجع:: The Complete JavaScript Course 2022 From Zero to Expert, https://developer.mozilla.org/en-US/docs/Web/API/Intersection_Observer_API


The Intersection Observer API provides a way to asynchronously observe changes in the intersection of a target element with an ancestor element or with a top-level document’s view port.

# Usage of Intersection

Intersection information is needed for many reasons, such as:

# Intersection Observer API Options

# The callback function

A function which is called when the percentage of the target element is visible crosses a threshold. The callback receives as input two parameters:

# How to use it?

# Examples

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
const section1 = document.querySelector('#section--1');  
  
const obsCallback = function (entries, observer) {  
  entries.forEach(entry => {  
    console.log(entry);  
  });  
};  
const obsOptions = {  
  root: null,  
  threshold: [0, 0.2],  
};  
const observer = new IntersectionObserver(obsCallback, obsOptions);  
observer.observe(section1);  

# Reveal Sections

1
2
3
4
.section--hidden {  
  opacity: 0;  
  transform: translateY(8rem);  
}  
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
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');  
});  

# Lazy-loading Images

1
2
3
4
5
6
<img  
  src="img/digital-lazy.jpg"  
  data-src="img/digital.jpg"  
  alt="Computer"  
  class="features__img lazy-img"  
/>  
1
2
3
.lazy-img {  
  filter: blur(20px);  
}  
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
// Lazy loading images  
const imgTargets = document.querySelectorAll('img[data-src]');  
  
const loadImg = function (entries, observer) {  
  const [entry] = entries;  
  
  if (!entry.isIntersecting) return;  
  
  // Replace src with data-src  
  entry.target.src = entry.target.dataset.src;  
  
  entry.target.addEventListener('load', function () {  
    entry.target.classList.remove('lazy-img');  
  });  
  
  observer.unobserve(entry.target);  
};  
  
const imgObserver = new IntersectionObserver(loadImg, {  
  root: null,  
  threshold: 0,  
  rootMargin: '200px',  
});  
  
imgTargets.forEach(img => imgObserver.observe(img));