Svelte

Embla Carousel provides a wrapper for Svelte that ensures seamless integration of the carousel into your Svelte project and automatic cleanup on component unmount.

Start by installing the Embla Carousel npm package and add it to your dependencies.

npm install embla-carousel-svelte --save

The component structure

Embla Carousel provides the handy emblaCarouselSvelte action for seamless integration with Svelte. A minimal setup requires an overflow wrapper and a scroll container. Start by adding the following structure to your carousel:

<script>  import emblaCarouselSvelte from 'embla-carousel-svelte'</script>
<div class="embla" use:emblaCarouselSvelte>  <div class="embla__container">    <div class="embla__slide">Slide 1</div>    <div class="embla__slide">Slide 2</div>    <div class="embla__slide">Slide 3</div>  </div></div>

The element with the classname embla is needed to cover the scroll overflow. Its child element with the container classname is the scroll body that scrolls the slides. Continue by adding the following CSS to these elements:

<style>  .embla {    overflow: hidden;  }  .embla__container {    display: flex;  }  .embla__slide {    flex: 0 0 100%;    min-width: 0;  }</style>

The emblaCarouselSvelte action takes the Embla Carousel options as part of its parameter. Additionally, you can access the API by using the emblaInit event to store the carousel instance in a variable:

<script>  import emblaCarouselSvelte from 'embla-carousel-svelte'
  let emblaApi  let options = { loop: false }
  function onInit(event) {    emblaApi = event.detail    console.log(emblaApi.slideNodes()) // Access API  }</script>
<div  class="embla"  use:emblaCarouselSvelte="{{ options }}"  onemblaInit="{onInit}">  <div class="embla__container">    <div class="embla__slide">Slide 1</div>    <div class="embla__slide">Slide 2</div>    <div class="embla__slide">Slide 3</div>  </div></div>

Note: Starting with Svelte 5, the on: event handlers have been deprecated. However, on:emblaInit will remain for backward compatibility.

Adding plugins

Start by installing the plugin you want to use. In this example, we're going to install the Autoplay plugin:

npm install embla-carousel-autoplay --save

The emblaCarouselSvelte action parameter accepts plugins. Note that plugins need to be passed in an array like so:

<script>  import emblaCarouselSvelte from 'embla-carousel-svelte'  import Autoplay from 'embla-carousel-autoplay'
  let options = { loop: false }  let plugins = [Autoplay()]</script>
<div class="embla" use:emblaCarouselSvelte="{{ options, plugins }}">  <div class="embla__container">    <div class="embla__slide">Slide 1</div>    <div class="embla__slide">Slide 2</div>    <div class="embla__slide">Slide 3</div>  </div></div>

Congratulations! You just created your first Embla Carousel component.

Edit this page on GitHub