Created
January 4, 2023 14:02
-
-
Save badabingbreda/28441c1263af6c9487d6880ad7be4236 to your computer and use it in GitHub Desktop.
Intersection observer that checks if a .buy-now button is in view
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* 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