JSFiddle - React, Tailwind, and code Playground
by thelevicole
HTML
<div class="carousel-container">
<div class="carousel">
<img src="https://picsum.photos/100/300" />
<img src="https://picsum.photos/200/300" />
<img src="https://picsum.photos/300/300" />
<img src="https://picsum.photos/400/300" />
<img src="https://picsum.photos/500/300" />
</div>
<button class="carousel-prev">
❮
</button>
<button class="carousel-next">
❯
</button>
</div>
CSS
/* Container styles BEFORE carousel has loaded */
.carousel-container {
opacity: 0.3;
pointer-events: none;
border: 2px solid red;
}
/* Container styles AFTER carousel has loaded */
.carousel-container.loaded {
opacity: 1;
pointer-events: auto;
border-color: green;
}
/* Hide all carousel slides by default */
.carousel-container .carousel > * {
display: none;
}
/* Only show the active carousel slide */
.carousel-container .carousel > *.active {
display: block;
}
JavaScript
class CarouselController {
/**
* @param {object} settings
*/
constructor(settings) {
this.carousel = settings.element;
this.current = 0;
if (!this.carousel) {
throw 'A carousel element is required. For example: new CarouselController({ element: document.getElementById(\'carousel\') })';
}
this.settings = {
loop: 'loop' in settings ? settings.loop : true,
delay: 'delay' in settings ? parseInt(settings.delay) : 5000
};
}
/**
* Get the carousel container element.
* @returns {Element}
*/
getCarousel() {
return this.carousel;
}
/**
* Get a setting value.
* @param {string} name
* @param defaultValue
* @returns {*}
*/
getSetting(name, defaultValue) {
return name in this.settings ? this.settings[name] : defaultValue;
}
/**
* Get all the children (slides) elements.
* @returns {Element[]}
*/
getSlides() {
return Array.from(this.getCarousel().children);
}
/**
* Get a specific slide by index.
* @param {int} index
* @returns {Element|null}
*/
getSlide(index) {
return this.getSlides()[index];
}
/**
* Show a specific slide by index.
* @param {int} index
* @returns {int}
*/
goTo(index) {
const slides = this.getSlides();
const slide = this.getSlide(index);
if (slide) {
slides.forEach((el) => {
el.classList.remove('active');
});
slide.classList.add('active');
this.current = slides.indexOf(slide);
}
return this.current;
}
/**
* Show the next slide (if has one).
*/
next() {
let replay = false;
// Check if carousel is looping through slides automatically.
if (this.playing) {
replay = true;
}
const slides =...