Image Carousel
Bildergalerie mit Navigation und Auto-Play.
Component HTML
html
<div class="max-w-4xl mx-auto">
<h2 class="text-2xl font-bold text-gray-900 mb-6">{{title}}</h2>
<div
data-island="image-carousel"
data-island-props='{"images": {{images}}, "autoplay": {{autoplay}}}'
>
<!-- Carousel Island rendert hier -->
</div>
</div>Island Code
javascript
// islands/image-carousel.js
export default class ImageCarouselIsland {
constructor(element, props = {}) {
this.element = element;
this.images = props.images || [];
this.autoplay = props.autoplay;
this.currentIndex = 0;
this.intervalId = null;
this.init();
}
init() {
this.render();
this.attachEvents();
if (this.autoplay) this.startAutoplay();
}
render() {
const img = this.images[this.currentIndex];
this.element.innerHTML = `
<div class="relative bg-gray-100 rounded-lg overflow-hidden">
<img src="${img.url}" alt="${img.alt}" class="w-full h-96 object-cover" />
<button class="prev absolute left-4 top-1/2 -translate-y-1/2 bg-black/50 text-white p-3 rounded-full hover:bg-black/70">
←
</button>
<button class="next absolute right-4 top-1/2 -translate-y-1/2 bg-black/50 text-white p-3 rounded-full hover:bg-black/70">
→
</button>
<div class="absolute bottom-4 left-1/2 -translate-x-1/2 flex gap-2">
${this.images.map((_, i) => `
<button class="dot w-2 h-2 rounded-full ${i === this.currentIndex ? 'bg-white' : 'bg-white/50'}"></button>
`).join('')}
</div>
</div>
`;
}
attachEvents() {
this.element.querySelector('.prev').addEventListener('click', () => this.prev());
this.element.querySelector('.next').addEventListener('click', () => this.next());
this.element.querySelectorAll('.dot').forEach((dot, i) => {
dot.addEventListener('click', () => this.goTo(i));
});
}
prev() {
this.currentIndex = (this.currentIndex - 1 + this.images.length) % this.images.length;
this.render();
this.attachEvents();
}
next() {
this.currentIndex = (this.currentIndex + 1) % this.images.length;
this.render();
this.attachEvents();
}
goTo(index) {
this.currentIndex = index;
this.render();
this.attachEvents();
}
startAutoplay() {
this.intervalId = setInterval(() => this.next(), 3000);
}
destroy() {
if (this.intervalId) clearInterval(this.intervalId);
}
}Was du lernst
- Intervals: Auto-Play mit setInterval/clearInterval
- Lifecycle: Setup und Cleanup von Timers
- Array Navigation: Zirkuläre Navigation durch Listen
- Event Handling: Multiple Buttons (prev, next, dots)