Skip to content

Instantly share code, notes, and snippets.

@mortennajbjerg
Created March 11, 2022 10:26
Show Gist options
  • Save mortennajbjerg/3944f1836c2027ee402edc55f9e7e1c5 to your computer and use it in GitHub Desktop.
Save mortennajbjerg/3944f1836c2027ee402edc55f9e7e1c5 to your computer and use it in GitHub Desktop.
JS Helper for InViewport & Tailwind animations
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