UNPKG

scroll-animate-builder

Version:

A lightweight DOM builder with scroll-triggered animations

2 lines (1 loc) 1.18 kB
(()=>{function u(t,e){return t.replace(/{{(.*?)}}/g,(o,c)=>e[c.trim()]??"")}function f(t,e={}){if(typeof t=="string")return document.createTextNode(u(t,e));if(!t||typeof t!="object")return null;let{tag:o,text:c,children:i=[],animate:a,...l}=t,r=document.createElement(o);c&&(r.textContent=u(c,e)),a===!0&&r.setAttribute("data-scroll","out");for(let[n,s]of Object.entries(l))n.startsWith("on")&&typeof s=="function"?r.addEventListener(n.slice(2).toLowerCase(),s):r.setAttribute(n,u(s,e));for(let n of i){let s=f(n,e);s&&r.appendChild(s)}return r}function p(){let t=new IntersectionObserver(e=>{e.forEach(o=>{o.isIntersecting?o.target.setAttribute("data-scroll","in"):o.target.setAttribute("data-scroll","out")})},{threshold:.1});document.querySelectorAll("[data-scroll]").forEach(e=>{t.observe(e)})}async function h(t,e){let o=typeof e=="string"?document.querySelector(e):e,c=t.api?await fetch(t.api).then(i=>i.json()):t.data||[];for(let i of c){let a=[];for(let[r,n]of Object.entries(t.mapEach||{}))if(i[r]!=null){let d=f({...typeof n=="string"?{tag:n}:n,text:`{{${r}}}`},i);d&&a.push(d)}let l=f(t.wrap||{tag:"div"});a.forEach(r=>l.appendChild(r)),o.appendChild(l)}p()}})();