Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR JAVASCRIPT

intersection observer API

//first we need to create new intersection observer
//we pass there callback function and object of options
//callback function will get called every time observed (target) element 
//intersecting the root element at the threshold that we defined.
//function will called with 2 arguments: threshold entries and observer
const header = document.querySelector(".header");
const navHeight = nav.getBoundingClientRect().height;

const stickyNav = function (entries) {
  const [entry] = entries;
  console.log(entry);
  if (!entry.isIntersecting) {
    nav.classList.add("sticky");
  } else {
    nav.classList.remove("sticky");
  }
};

const obsOptions = {
  root: null,
  threshold: 0, //when element is hidden from viewport
  rootMargin: `-${navHeight}px`,
};

const headerObserver = new IntersectionObserver(stickyNav, obsOptions);
headerObserver.observe(header);

//Stop observing
//Observer is argument in callback function
observer.unobserve(entry.target);
 
PREVIOUS NEXT
Tagged: #intersection #observer #API
ADD COMMENT
Topic
Name
5+9 =