UNPKG

observe-element-in-viewport

Version:

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

3 lines (2 loc) 1.35 kB
!function(o,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports):"function"==typeof define&&define.amd?define(["exports"],e):e(o.observeElementInViewport={})}(this,function(o){function e(o,e,t,r){if(void 0===t&&(t=function(){}),void 0===r&&(r={}),!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]},r),i=n.viewport,f=n.modTop,s=n.modLeft,u=n.modBottom,a=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 p=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,p),m={root:i instanceof Node?i:null,rootMargin:f+" "+a+" "+u+" "+s,threshold:p},h=new IntersectionObserver(function(r,n){var i=r.filter(function(e){return e.target===o})[0],f=function(){return n.unobserve(o)};i&&(i.isInViewport=i.isIntersecting&&i.intersectionRatio>=c,i.isInViewport?e(i,f,o):t(i,f,o))},m);return h.observe(o),function(){return h.unobserve(o)}}o.observeElementInViewport=e,o.isInViewport=function(o,t){return void 0===t&&(t={}),new Promise(function(r,n){try{e(o,function(o,e){e(),r(!0)},function(o,e){e(),r(!1)},t)}catch(o){n(o)}})}}); //# sourceMappingURL=index.umd.js.map