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);
  // let stillIntersecting;

  // const waitForThreeSecondsTimeOut = (observer, targetTestimonialModule) => {
  //   setTimeout(() => {
  //     if (stillIntersecting) {
  //       // log('3 seconds yeah!');
  //       setAttributes({
  //         acrns264_user_sees_testimonials_module: 'true',
  //       });
  //       log('attribute set --- acrns264_user_sees_testimonials_module: true');
  //       observer.unobserve(targetTestimonialModule);
  //     }
  //   }, 3000);
  // };
 

  // utils.waitForElement('.card.marissa-card').then((targetTestimonialModule) => {
  //   const observer = new IntersectionObserver((entries, observer) => {
  //     entries.forEach((entry) => {
  //       if (entry.isIntersecting) {
  //         stillIntersecting = true;
  //         waitForThreeSecondsTimeOut(observer, targetTestimonialModule);
  //       } 

  //       if (!entry.isIntersecting) {
  //         stillIntersecting = false;
  //         clearTimeout(waitForThreeSecondsTimeOut);
  //         // log('user did not view testimonial for 3 seconds');
  //       }
  //     });
  //   }, {
  //     threshold: 1.0,
  //   });

  //   observer.observe(targetTestimonialModule);
  // }).catch(error);
 const options = {
    root: document.getElementById('some-id'), // leave blank for viewport
    rootMargin: '0px',
    threshold: 1.0,
  };
  
  const observer = new IntersectionObserver(observeTestamonialInViewPortCB, options);

  const observeTestamonialInViewPortCB = (entries, observer) => {
    entries.forEach((entry) => {
      log(entry);
	// to stop observer:
	observer.unobserve();
    });
  };

  const target = document.getElementById('target-element');
  observer.observe(target);
    const slickTrack = document.querySelector(`.slick-track`);
    new MutationObserver((entries) => {
      entries.forEach((mutationRecord) => {
        if (photosSwipedOrButtonsCLicked) return;
        log('style has transition: ', mutationRecord.target.getAttribute('style').includes('transition'));
        if (mutationRecord.target.getAttribute('style').includes('transition')) {
          sendEvent(100322757);
          photosSwipedOrButtonsCLicked = true;
        } else {
          log('targeted mutation does not include transition style');
        }
      });
    }).observe(slickTrack, {
      attributes: true,
    }); 
const endpoint = 'https://gist.githubusercontent.com/Miserlou/c5cd8364bf9b2420bb29/raw/2bf258763cdddd704f8ffd3ea9a3e81d25e2c6f6/cities.json';
const cities = [];
const searchInput = document.querySelector('.search');
const suggestions = document.querySelector('.suggestions');

const fetchData = async(url) => {
    const response = await fetch(url)
    const data = await response.json();
    return data;
}


function displayItems(cities){
    const items = cities.map((place) => {
      return `
      <li>
        <span class="name">${place.city}</span>
        <span class="population">${place.population}</span>
      </li>
    `;
  }).join('');
  suggestions.innerHTML = items;

}



const startApp = async() => {

    const citiesData = await fetchData(endpoint);
    cities.push(...citiesData);  
    displayItems(cities)

    searchInput.addEventListener('keyup', function(e){
      const value = e.target.value;
      const regex = new RegExp(value, 'gi');
      const filteredCities = cities.filter((place) => {
       return place.city.match(regex);
      })

      displayItems(filteredCities);
    })

}


startApp();












function removeTransition(e){
  console.log(e.propertyName)
  // can do a condition based on a property or add a property using setProperty
  //example
  
   this.style.setProperty("background-color", 'blue');
  
  // a a consition to
 	if(e.propertyName !== 'transform') return
  	this.classList.remove('playing');
 
}


const keys = [...document.querySelectorAll('.key')]; //loop over all items clicked
keys.forEach((key) => key.addEventListener('transitionend', removeTransition))
// Select the node that will be observed for mutations
const targetNode = document.getElementById("some-id");

// Options for the observer (which mutations to observe)
const config = { attributes: true, childList: true, subtree: true };

// Callback function to execute when mutations are observed
const callback = (mutationList, observer) => {
  for (const mutation of mutationList) {
    if (mutation.type === "childList") {
      console.log("A child node has been added or removed.");
    } else if (mutation.type === "attributes") {
      console.log(`The ${mutation.attributeName} attribute was modified.`);
    }
  }
};

// Create an observer instance linked to the callback function
const observer = new MutationObserver(callback);

// Start observing the target node for configured mutations
observer.observe(targetNode, config);

// Later, you can stop observing
observer.disconnect();
const sections = document.querySelector('.section--2');

const options = {
  rootMargin: '0px',
  threshold: 0.8
}

function handleSections(entries){
    entries.forEach((entry) => {
    if(entry.isIntersecting){
     entry.target.classList.add()
    }else{
      entry.target.style.backgroundColor = 'transparent'
    }
    })
}

const sectionObserver = new IntersectionObserver(handleSections, options);

sectionObserver.observe(sections)
// intersection observer using a function
const ObserverTemplate = () => {

  const options = {
    rootMargin: '0px 0px -200px 0px',
    threshold: 0.5
  }

  const textObserver = new IntersectionObserver((entries) => {

      entries.forEach((entry) => {
            if(entry.isIntersecting){
              entry.target.classList.add('show')
            }else{
              entry.target.classList.remove('show')
            }
      })
  }, options)

  const h1Tag = getElement('h1')
  // console.log(h1Tag)

  textObserver.observe(h1Tag)
  
}



window.addEventListener('DOMContentLoaded', ObserverTemplate)
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
star

Wed May 10 2023 16:23:16 GMT+0000 (Coordinated Universal Time)

#intersection #observer
star

Wed Apr 19 2023 17:10:01 GMT+0000 (Coordinated Universal Time)

#intersection #observer
star

Tue Apr 04 2023 19:48:17 GMT+0000 (Coordinated Universal Time)

#optimizely #mutation #observer
star

Mon Feb 27 2023 04:26:43 GMT+0000 (Coordinated Universal Time)

#intersection #observer
star

Sun Feb 26 2023 22:30:54 GMT+0000 (Coordinated Universal Time)

#intersection #observer
star

Thu Feb 23 2023 00:39:42 GMT+0000 (Coordinated Universal Time)

#mutation #observer
star

Fri Dec 30 2022 04:35:36 GMT+0000 (Coordinated Universal Time)

#intersection #observer
star

Fri Dec 30 2022 04:33:48 GMT+0000 (Coordinated Universal Time)

#intersection #observer

Save snippets that work with our extensions

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