UNPKG

observe-element-in-viewport

Version:

Wrapper around IntersectionObserver to hide away its weirdness and increase ease of usability

3 lines (2 loc) 1.18 kB
function o(o,r,t,e){if(void 0===t&&(t=function(){}),void 0===e&&(e={}),!o)throw new Error("Target element to observe should be a valid DOM Node");var n=Object.assign({},{viewport:null,modTop:"0px",modRight:"0px",modBottom:"0px",modLeft:"0px",threshold:[0]},e),i=n.viewport,a=n.modTop,u=n.modLeft,s=n.modBottom,f=n.modRight,d=n.threshold;if(!Array.isArray(d)&&"number"!=typeof d)throw new Error("threshold should be a number or an array of numbers");var h=Array.isArray(d)?d.map(function(o){return Math.floor(o%101)/100}):[Math.floor(d?d%101:0)/100],c=Math.min.apply(Math,h),m={root:i instanceof Node?i:null,rootMargin:a+" "+f+" "+s+" "+u,threshold:h},l=new IntersectionObserver(function(e,n){var i=e.filter(function(r){return r.target===o})[0],a=function(){return n.unobserve(o)};i&&(i.isInViewport=i.isIntersecting&&i.intersectionRatio>=c,i.isInViewport?r(i,a,o):t(i,a,o))},m);return l.observe(o),function(){return l.unobserve(o)}}var r=function(r,t){return void 0===t&&(t={}),new Promise(function(e,n){try{o(r,function(o,r){r(),e(!0)},function(o,r){r(),e(!1)},t)}catch(o){n(o)}})};export{o as observeElementInViewport,r as isInViewport}; //# sourceMappingURL=index.esm.js.map