document.addEventListener('DOMContentLoaded', function(event) { function start(element) { window.requestAnimationFrame(function () { // Custom Attributes element.style.animationDelay = element.dataset.animationDelay; element.style.animationDuration = element.dataset.animationDuration; // Initiate animation from class element.classList.add(element.dataset.animation); // Set the element as animated element.dataset.animated = "true"; }); }; function inViewport(element){ let offset = 15; const windowTop = offset * window.innerHeight / 100; const windowBottom = window.innerHeight - windowTop; const windowLeft = 0; const windowRight = window.innerWidth; // Get bounding box element const elementRect = element.getBoundingClientRect(); const elementTop = elementRect.top + parseInt(element.dataset.animationOffset) || elementRect.top; const elementBottom = elementRect.bottom - parseInt(element.dataset.animationOffset) || elementRect.bottom; const elementLeft = elementRect.left; const elementRight = elementRect.right; // Verify where element's positioned return ( elementTop <= windowBottom && elementBottom >= windowTop && elementLeft <= windowRight && elementRight >= windowLeft); }; // Find the array of elements, verify that the element is on the screen and initiate the animation function verifyElementsInViewport(els = elements) { for (let i = 0, len = els.length; i < len; i++) { // Go to the nearest location where element is + stay animated if (els[i].dataset.animated) continue; if(inViewport(els[i])){ start(els[i]); } } }; // Get all elements to be animated function getElements(){ return document.querySelectorAll("[data-animation]:not([data-animated])"); } function update() { console.log("on Page load Animate"); let elements = getElements(); if (elements ){ verifyElementsInViewport(elements); } }; update(); var pageWrapper = document.getElementsByClassName('main-wrapper'); console.log(pageWrapper.length); if(pageWrapper.length > 0){ pageWrapper[0].addEventListener('scroll', function(){ console.log('scroll') let elements = getElements(); if (elements ){ verifyElementsInViewport(elements); } }); } window.addEventListener('scroll', function() { console.log("on Scroll Animate"); let elements = getElements(); if (elements ){ verifyElementsInViewport(elements); } }); window.addEventListener('resize', function() { console.log("on Resize Animate"); let elements = getElements(); if (elements ){ verifyElementsInViewport(elements); } }); });