UNPKG

dxb-parallax

Version:

A vanilla JavaScript parallax scrolling plugin, a port of Ian Lunn’s jQuery Parallax v1.1.3

1 lines 1.34 kB
class Parallax{static#t=new Set;static#e=window.innerHeight;static#a=!1;static#i=!1;constructor(t,{xpos:e="50%",speedFactor:a=.1,outerHeight:i=!0}={}){if(!(t instanceof Element))throw new TypeError("Parallax expects a DOM Element");this.el=t,this.xpos=e,this.speedFactor=a,this.getHeight=i?t=>t.offsetHeight:t=>t.clientHeight;const{top:n}=this.el.getBoundingClientRect();this.firstTop=n+window.scrollY,Parallax.#t.add(this),Parallax.#n(),this.#s()}static#n(){Parallax.#i||(Parallax.#i=!0,window.addEventListener("resize",(()=>{Parallax.#e=window.innerHeight,Parallax.#l()}),{passive:!0}),window.addEventListener("scroll",Parallax.#l,{passive:!0}))}static#l(){Parallax.#a||(Parallax.#a=!0,requestAnimationFrame(Parallax.#r))}static#r(){Parallax.#t.forEach((t=>t.#s())),Parallax.#a=!1}#s(){const t=window.scrollY,e=this.el.getBoundingClientRect().top+window.scrollY;if(e+this.getHeight(this.el)<t||e>t+Parallax.#e)return;const a=Math.round((this.firstTop-t)*this.speedFactor);this.el.style.backgroundPosition=`${this.xpos} ${a}px`}destroy(){Parallax.#t.delete(this),Parallax.#t.size||(window.removeEventListener("scroll",Parallax.#l),window.removeEventListener("resize",Parallax.#l),Parallax.#i=!1)}}function parallax(t,e){return("string"==typeof t?document.querySelectorAll(t):t instanceof Element?[t]:Array.from(t)).map((t=>new Parallax(t,e)))}