Skip to content

Instantly share code, notes, and snippets.

@badabingbreda
Created January 4, 2023 14:02
Show Gist options
  • Save badabingbreda/28441c1263af6c9487d6880ad7be4236 to your computer and use it in GitHub Desktop.
Save badabingbreda/28441c1263af6c9487d6880ad7be4236 to your computer and use it in GitHub Desktop.
Intersection observer that checks if a .buy-now button is in view
/*
* function to add observer
*/
function inViewport(selector, callback, options = {}) {
const elems = document.querySelectorAll( selector );
function observerCallback(entries, observer) {
entries.forEach(entry => callback(entry))
};
const observer = new IntersectionObserver( observerCallback , options );
elems.forEach( (i) => {
if (i) { observer.observe(i); }
})
}
inViewport('.buy-now',
entry => {
// returns true or false
if (entry.isIntersecting) {
document.querySelector( 'body' ).classList.add( 'buy-now-in-view' );
} else {
document.querySelector( 'body' ).classList.remove( 'buy-now-in-view' );
}
},
{ root: null } // use browser viewport
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment