Created
March 11, 2022 10:26
-
-
Save mortennajbjerg/3944f1836c2027ee402edc55f9e7e1c5 to your computer and use it in GitHub Desktop.
JS Helper for InViewport & Tailwind animations
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
import inViewport from 'in-viewport'; | |
/** | |
* Use like this: | |
* | |
* <div class="transition duration-500" data-inview-before="opacity-0" data-inview-after="opacity-100">Fade me in</div> | |
*/ | |
document.addEventListener('DOMContentLoaded', () => { | |
var inviewEls = document.querySelectorAll('[data-inview'); | |
if (!inviewEls || inviewEls.length === 0) { | |
return false; | |
} | |
for (const el of inviewEls) { | |
let beforeClasses = el.getAttribute('data-inview-before') ? el.getAttribute('data-inview-before').split(' ') : []; | |
let afterClasses = el.getAttribute('data-inview-after') ? el.getAttribute('data-inview-after').split(' ') : []; | |
el.classList.add(...beforeClasses); | |
inViewport(el, () => { | |
el.classList.remove(...beforeClasses) | |
el.classList.add(...afterClasses); | |
}); | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment