UNPKG

@sarawebs/sb-components

Version:

SaraWebs components for web apps and tools

3 lines (2 loc) 2.63 kB
class t{constructor(t,e=[],s=5e3){const i=document.createElement("div");i.classList.add("carousel"),t.appendChild(i),this.root=i,this.images=e,this.autoSlideDelay=s,this.currentSlide=0,this.timer=null,this.buildCarousel(),this.cacheElements(),this.init()}buildCarousel(){this.root.innerHTML="";const t=document.createElement("div");t.classList.add("carousel-track-container");const e=document.createElement("ul");e.classList.add("carousel-track"),this.images.forEach(t=>{const s=document.createElement("li");s.classList.add("carousel-slide");const i=document.createElement("img");i.src=t,s.appendChild(i),e.appendChild(s)}),t.appendChild(e),this.root.appendChild(t);const s=document.createElement("button");s.className="carousel-button left",s.innerHTML="&#10094;";const i=document.createElement("button");i.className="carousel-button right",i.innerHTML="&#10095;",this.root.appendChild(s),this.root.appendChild(i);const o=document.createElement("div");o.className="carousel-nav",this.images.forEach((t,e)=>{const s=document.createElement("button");s.className="carousel-indicator",0===e&&s.classList.add("current-slide"),o.appendChild(s)}),this.root.appendChild(o)}cacheElements(){this.track=this.root.querySelector(".carousel-track"),this.slides=Array.from(this.track.children),this.prevBtn=this.root.querySelector(".carousel-button.left"),this.nextBtn=this.root.querySelector(".carousel-button.right"),this.nav=this.root.querySelector(".carousel-nav"),this.dots=Array.from(this.nav.children),this.slideWidth=this.slides[0].getBoundingClientRect().width}init(){this.setSlidePositions(),this.prevBtn.addEventListener("click",()=>this.moveToSlide(this.currentSlide-1)),this.nextBtn.addEventListener("click",()=>this.moveToSlide(this.currentSlide+1)),this.dots.forEach((t,e)=>{t.addEventListener("click",()=>this.moveToSlide(e))}),this.startAutoSlide(),this.root.addEventListener("mouseenter",()=>this.stopAutoSlide()),this.root.addEventListener("mouseleave",()=>this.startAutoSlide())}setSlidePositions(){this.slideWidth=this.slides[0].getBoundingClientRect().width,this.slides.forEach((t,e)=>{t.style.left=this.slideWidth*e+"px"})}moveToSlide(t){t<0&&(t=this.slides.length-1),t>=this.slides.length&&(t=0);const e=-this.slideWidth*t;this.track.style.transform=`translateX(${e}px)`,this.dots[this.currentSlide].classList.remove("current-slide"),this.dots[t].classList.add("current-slide"),this.currentSlide=t}startAutoSlide(){this.stopAutoSlide(),this.timer=setInterval(()=>{this.moveToSlide(this.currentSlide+1)},this.autoSlideDelay)}stopAutoSlide(){clearInterval(this.timer)}}export{t as Carousel}; //# sourceMappingURL=index.js.map