Snippets Collections
 const options = {
        rootMargin: '0px 0px -200px 0px'
    }

    const observer = new IntersectionObserver((entries, observer) => {
        entries.forEach(entry => {
            if(entry.isIntersecting) {
                entry.target.classList.add('show');
                observer.unobserve(entry.target);
            } else {
                return;
            }
        })
    }, options);

    const h1 = document.querySelector('h1'); // targets one element
    observer.observe(h1);

    const paras = document.querySelectorAll('p'); 
    paras.forEach(p => observer.observe(p)); //targets multple element with a loop
// Callback function to execute when intersections are detected

const callback = (entries, observer) => {
  entries.forEach(entry => {
    if (entry.isIntersecting) {
      console.log('Element is in view');
      // Perform actions like loading images, animations, etc.
    } else {
      console.log('Element is out of view');
    }
  });
};

// Options object

const options = {
  root: null, // relative to the viewport
  rootMargin: '0px', // margin around the root
  //threshold: 0.1 // trigger callback when 10% of the element is visible
  treshold: 0, //means out of the viewport
};

// Create an instance of IntersectionObserver with the callback and options

const observer = new IntersectionObserver(callback, options);

// Target element to be observed

const target = document.querySelector('.target-element');

// Start observing the target element

observer.observe(target);
star

Fri Jul 05 2024 00:40:42 GMT+0000 (Coordinated Universal Time)

#scroll #intersectionobserver #observer
star

Thu Jul 04 2024 23:50:15 GMT+0000 (Coordinated Universal Time)

#scroll #intersectionobserver #observer

Save snippets that work with our extensions

Available in the Chrome Web Store Get Firefox Add-on Get VS Code extension