Created
March 12, 2019 15:17
-
-
Save LiamChapman/0f7c134ecadd0249e45511d2a85d7f8e to your computer and use it in GitHub Desktop.
Intersection Observer Helper Function
This file contains hidden or 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
| // Polyfill | |
| if (typeof window !== 'undefined') { | |
| require('intersection-observer'); // eslint-disable-line global-require | |
| } | |
| // when elements intersect add css class | |
| export default ({ | |
| elements, | |
| threshold, | |
| root = null, | |
| rootMargin = '0px', | |
| }) => { | |
| const options = { | |
| root, | |
| rootMargin, | |
| threshold, | |
| }; | |
| const observer = new IntersectionObserver((entries) => { | |
| for (let x = 0; x < entries.length; x += 1) { | |
| const entry = entries[x]; | |
| if (entry.isIntersecting) entry.target.classList.add(entry.target.dataset.classToAdd); | |
| } | |
| }, options); | |
| for (let i = 0; i < elements.length; i += 1) { | |
| observer.observe(elements[i]); | |
| } | |
| }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment