v1.1.6 TwistedAndy/better-carousel

Better Carousel

A small, fast and accessible carousel. Your grid of cards becomes a carousel with the same HTML and CSS. The motion runs on the compositor, also on slow phones.

13.3 KB gzipped MIT license No dependencies
Getting started

Installation

Better Carousel is one JavaScript file and one stylesheet. It has no dependencies.

Script tag

Add the stylesheet and the script to the page. The script adds the global BetterCarousel function. This page uses the library in this way.

HTML
<link rel="stylesheet" href="dist/better-carousel.css">
<script src="dist/better-carousel.min.js"></script>

npm

Install the package. Then import the script and the stylesheet.

Terminal
npm install @twistedandy/better-carousel
JavaScript
import BetterCarousel from '@twistedandy/better-carousel';
import '@twistedandy/better-carousel/css';

Files

FileFormatUse
dist/better-carousel.min.jsIIFE, minifiedFor a script tag. It adds the global BetterCarousel function.
dist/better-carousel.jsES moduleFor a bundler: import BetterCarousel from '@twistedandy/better-carousel'.
dist/better-carousel.cssCSSThe styles with the default class names.
src/types/better-carousel.d.tsTypeScriptThe types. TypeScript and the editors find them automatically.
src/styles/better-carousel.scssSCSSThe styles with your class names (see Styling).

Quick start

A carousel is a container with slides. Your CSS gives the container a row layout, and the library moves the container.

Add the slides

Put the slides into a container, and make the container a flex row.

Use your own class names. The library takes each child of the container as a slide, so items and item are only examples.

HTML
<div class="items carousel">
  <div class="item"><img src="photo-1.jpg" alt="Photo 1"></div>
  <div class="item"><img src="photo-2.jpg" alt="Photo 2"></div>
  <div class="item"><img src="photo-3.jpg" alt="Photo 3"></div>
  <div class="item"><img src="photo-4.jpg" alt="Photo 4"></div>
</div>

Set the space between the slides with gap:

CSS
/* 3 slides with 2 gaps of 20px */
.items {
  display: flex;
  gap: 20px;
}

.items .item {
  flex: none;
  width: calc((100% - 40px) / 3);
}

Or set the space with margins. A negative margin of the container cancels the margin of the last slide:

CSS
/* 3 slides with 20px between them */
.items {
  --gap: 20px;
  display: flex;
  width: calc(100% + var(--gap));
  margin-right: calc(-1 * var(--gap));
}

.items .item {
  flex: none;
  width: calc(100% / 3 - var(--gap));
  margin-right: var(--gap);
}

margin-left and margin-inline-end also work. Use margin-inline-end for a carousel that can be right-to-left.

Start the carousel

JavaScript
// One carousel
const carousel = BetterCarousel(document.querySelector('.items'));

// All carousels on the page
const carousels = BetterCarousel.initAll('.items.carousel');

The library puts the container into a viewport, and adds the arrows and the dots. It reads the size of the slides, the gap, the axis and the alignment from your CSS. Then it moves only the container. The How it works section shows the markup that the library adds.

Turn a grid into a carousel

A grid of cards can become a carousel with the same HTML. Add a class, such as carousel, with one or two CSS rules. Without this class, the cards show as a grid.

  • In a flex layout, set flex-wrap: nowrap. Set flex: none on the cards, so that they do not shrink.
  • In a CSS grid, set grid-auto-flow: column and grid-template-columns: none. Set the width of a card in grid-auto-columns. Do not use fr, because it divides the width of the container between all cards. For more rows, set grid-template-rows, such as repeat(2, auto) (example).
CSS
/* A flex layout */
.items {
  display: flex;
  flex-wrap: wrap;
  gap: 20px;
}

.items .item {
  flex: none;
  width: calc((100% - 40px) / 3);
}

.items.carousel {
  flex-wrap: nowrap;
}
CSS
/* A CSS grid */
.items {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 20px;
}

.items.carousel {
  grid-auto-flow: column;
  grid-template-columns: none;
  grid-auto-columns: calc((100% - 40px) / 3);
}

A width in percent is relative to the width of the carousel. To show a different number of cards on a phone, change the width in a media query.

How it works

The library puts the container into a viewport and a root. Then it adds the arrows and the dots to the root:

HTML
<div class="better" role="region" aria-roledescription="carousel" aria-label="Carousel">
  <div class="better_viewport">
    <div class="items carousel better_container">
      <div class="item">...</div>
    </div>
  </div>
  <button class="better_button better_prev" aria-label="Previous slide"></button>
  <button class="better_button better_next" aria-label="Next slide"></button>
  <div class="better_dots">...</div>
</div>
TermMeaning
RootThe outer element. It holds the viewport, the arrows and the dots. The library adds it if the page does not have it.
ViewportThe element that clips the slides. Its size is the visible area.
ContainerThe element that moves. Your CSS sets its layout, and the library sets its translate.
SlideA child of the container, or an element that matches the slides selector.
SnapA position where the carousel can stop. A snap shows one slide or a group of slides.
Selected snapThe snap that shows now. selectedSnap() gives its index.
Selected slideThe slide at the selected snap. It gets the selected class. selectedSlide() gives its index.
CloneA copy of a slide that the loop adds when the slides are too few. Clones are not in slideNodes(), and they have no index. A change in the content of a slide also changes its clones.
MotionA change of position with an animation. When a motion stops, the settle event occurs.
FitAll slides show in the viewport. The carousel does not move, and it does not show the arrows and the dots (example).

A carousel can have fewer snaps than slides. For example, slidesPerSnap: 2 puts two slides into each snap. Also, containScroll: 'trimSnaps' removes the snaps that show empty space at the ends. For this reason, the methods use two types of index:

  • goToSnap(), selectedSnap() and snapProgress() use a snap index.
  • goToSlide(), selectedSlide(), slidesInView() and slideNodes() use a slide index.
  • snapOfSlide(index) gives the snap index of a slide.

Each example on this page shows its selected snap and its selected slide under the carousel.

CSS layout

The library does not set the size of the slides or the space between them. It reads these values from the CSS and moves only the container. For this reason, one carousel can show 1 slide on a phone and 4 slides on a desktop, with no change in the script.

The CSS of the containerThe result
display: flex, a rowA horizontal carousel
flex-direction: columnA vertical carousel (example)
display: grid with grid-auto-flow: columnA horizontal carousel with more rows (example)
justify-content: centerThe selected slide is in the center (example)
justify-content: flex-endThe selected slide is at the end (example)
gap, column-gap or row-gapThe space between the slides. In a loop, also the space between the last slide and the first slide.
The margins of the slides and a negative margin of the containerThe same, for a layout without gap. The library adds the margins to the gap.
direction: rtlA right-to-left carousel
The padding of the viewportThe snaps align to the inner edge of the padding. The padding shows parts of the slides next to the selected slide.

The carousel measures again when the CSS changes, when the page adds or removes a slide, and when an image loads. A slide with display: none gets no snap. The template, script and style elements in the container are not slides. A CSS scale or zoom on a parent, such as the open animation of a modal window, does not change the snaps.

A horizontal carousel gets its width from its parent, not from its slides, so it does not overflow a flex item or a grid column. For this reason, a parent that gets its width from its content, such as an inline-block element or a flex item with no flex value, must have a width.

Configuration

Set the options in the call, in the data-carousel attribute, or in BetterCarousel.defaults for all carousels. If the call and the attribute set the same option, the value of the attribute applies.

JavaScript
// All carousels of the site
BetterCarousel.defaults = { loop: true, dragThreshold: 2 };

// One carousel
BetterCarousel(element, { align: 'center', dots: false });

// Other options for a media query
BetterCarousel(element, {
  breakpoints: {
    '(min-width: 1024px)': { drag: false }
  }
});

Write the value of data-carousel in JSON:

HTML
<div class="items items_4 carousel" data-carousel='{"loop":true,"autoplay":3000}'>
  <div class="item">...</div>
  <div class="item">...</div>
  <div class="item">...</div>
  ...
</div>

These options need no example of their own:

JavaScript
BetterCarousel(element, {
  startSnap: 2,          // Start at the third snap
  duration: 600,         // The duration of a motion by one snap, in ms
  inViewThreshold: 0.5,  // A slide is in view when half of it shows
  resize: false,         // Do not measure again when a size changes
  slideChanges: false,   // Do not watch for added and removed slides
  wrapper: false,        // Add no root and viewport: the page has them
});

The Options reference gives all options and their default values.

Styling

The stylesheet has the rules that the carousel needs. It also has the look of the arrows, the dots and the play button. To change the colors, set the CSS variables. To change the class names, compile the SCSS file.

CSS variables

The buttons and the dots use the button variables of the theme. The dots use --button-text-disabled, and the selected dot uses --button-base. The arrow icon is an inline SVG in the stylesheet. To use a different icon, set --button-arrow.

CSS
:root {
  --height-button: 2.5rem;         /* The size of the buttons */
  --button-arrow: url(arrow.svg);  /* Optional: the default is a chevron */

  --button-border: #7c3aed;
  --button-base: #7c3aed;
  --button-text: #fff;
  --button-border-active: #6d28d9;
  --button-base-active: #6d28d9;
  --button-text-active: #fff;
  --button-border-disabled: #e8e8e8;
  --button-base-disabled: #f5f5f5;
  --button-text-disabled: #74787d;
}

SCSS

The SCSS file uses @import and global variables, so it compiles with Dart Sass and with node-sass. Set the variables before the import:

SCSS
// The class prefix: .embla, .embla_viewport, .embla_button
$better: 'embla';

// The prefix of the state classes: .is_selected, .is_current
$better-state: 'is_';

// Only the rules that the carousel needs: no look for the buttons and the dots
$better-look: false;

// The default icon of the arrows. The --button-arrow variable comes first.
$better-arrow: url(arrow.svg);

@import 'better-carousel';

Then set the same names in the options: { classes: 'embla', state: 'is_' }. The Classes reference gives all names.

Frameworks

Start the carousel when the component mounts, and destroy it before the component unmounts. The library does not move the elements that the framework controls.

  1. Render the root and the viewport in the component.
  2. When the component mounts, start the carousel on the viewport. The library finds the container in the viewport and adds no wrapper.
  3. Before the component unmounts, destroy the carousel.

React

Start the carousel in useEffect. Destroy it in the cleanup function. In Strict Mode, React runs each effect two times in development. The cleanup function destroys the first carousel, and the second carousel replaces it.

React
import { useEffect, useRef } from 'react';
import BetterCarousel from '@twistedandy/better-carousel';
import '@twistedandy/better-carousel/css';

export default function Carousel({ slides, options }) {
  const viewport = useRef(null);
  const carousel = useRef(null);

  useEffect(() => {
    carousel.current = BetterCarousel(viewport.current, options);
    return () => carousel.current.destroy();
  }, []);

  return (
    <>
      <div className="better">
        <div className="better_viewport" ref={viewport}>
          <div className="items items_3">
            {slides.map((slide) => (
              <div className="item" key={slide.id}>
                <img src={slide.src} alt={slide.alt} />
              </div>
            ))}
          </div>
        </div>
      </div>
      <button type="button" onClick={() => carousel.current.goToNext()}>Next slide</button>
    </>
  );
}

Vue

Start the carousel in onMounted. Destroy it in onBeforeUnmount.

Vue
<script setup>
import { onMounted, onBeforeUnmount, ref } from 'vue';
import BetterCarousel from '@twistedandy/better-carousel';
import '@twistedandy/better-carousel/css';

const props = defineProps({ slides: Array, options: Object });
const viewport = ref(null);
let carousel = null;

onMounted(() => {
  carousel = BetterCarousel(viewport.value, props.options);
});

onBeforeUnmount(() => carousel?.destroy());
</script>

<template>
  <div class="better">
    <div ref="viewport" class="better_viewport">
      <div class="items items_3">
        <div v-for="slide in slides" :key="slide.id" class="item">
          <img :src="slide.src" :alt="slide.alt">
        </div>
      </div>
    </div>
  </div>
</template>

Svelte

Start the carousel in onMount. The function that onMount returns destroys the carousel. This example is for Svelte 5. For Svelte 4, use export let slides and export let options in place of $props().

Svelte
<script>
  import { onMount } from 'svelte';
  import BetterCarousel from '@twistedandy/better-carousel';
  import '@twistedandy/better-carousel/css';

  let { slides, options } = $props();
  let viewport;

  onMount(() => {
    const carousel = BetterCarousel(viewport, options);
    return () => carousel.destroy();
  });
</script>

<div class="better">
  <div class="better_viewport" bind:this={viewport}>
    <div class="items items_3">
      {#each slides as slide (slide.id)}
        <div class="item">
          <img src={slide.src} alt={slide.alt}>
        </div>
      {/each}
    </div>
  </div>
</div>

Solid

Start the carousel in onMount. Destroy it with onCleanup.

Solid
import { onMount, onCleanup, For } from 'solid-js';
import BetterCarousel from '@twistedandy/better-carousel';
import '@twistedandy/better-carousel/css';

export default function Carousel(props) {
  let viewport;

  onMount(() => {
    const carousel = BetterCarousel(viewport, props.options);
    onCleanup(() => carousel.destroy());
  });

  return (
    <div class="better">
      <div class="better_viewport" ref={viewport}>
        <div class="items items_3">
          <For each={props.slides}>
            {(slide) => (
              <div class="item">
                <img src={slide.src} alt={slide.alt} />
              </div>
            )}
          </For>
        </div>
      </div>
    </div>
  );
}

Rules for frameworks

  • Do not render other elements after the viewport in the root. The library adds the arrows and the dots at the end of the root. To put them in a different element, set the arrows and dots options.
  • To change the options, call reinit(newOptions). The selected slide stays.
  • With server-side rendering, start the carousel only in the browser: in useEffect, onMounted or onMount. The library needs the DOM.

NOTE: When the framework adds or removes a slide, the carousel measures again. A reinit() call is not necessary.

Layout

Start alignment

Three slides show in the viewport. The selected slide is at the start of the viewport. Drag or swipe the slides, or use the arrows and the dots.

HTML
<div class="items items_3 carousel">
  <div class="item"><img src="photo.jpg" alt=""></div>
  <div class="item"><img src="photo.jpg" alt=""></div>
  <div class="item"><img src="photo.jpg" alt=""></div>
  ...
</div>
JavaScript
BetterCarousel.initAll('.items.carousel');

Center alignment

Four slides show in the viewport. The container has justify-content: center, so the selected slide is in the center, and parts of the slides at its sides show at the edges. At the first and the last slide, the carousel stops at the edge, so that no empty space shows at the ends.

HTML
<div class="items items_4 carousel is_center">
  <div class="item"><img src="photo.jpg" alt=""></div>
  <div class="item"><img src="photo.jpg" alt=""></div>
  <div class="item"><img src="photo.jpg" alt=""></div>
  ...
</div>
CSS
.items.is_center {
  justify-content: center;
}

To keep the empty space at the ends, set containScroll: false. The Space at the ends section shows the options.

End alignment

Four slides show in the viewport. The container has justify-content: flex-end, so the selected slide is at the end of the viewport, and the slides before it show at its left.

HTML
<div class="items items_4 carousel is_end">
  <div class="item"><img src="photo.jpg" alt=""></div>
  <div class="item"><img src="photo.jpg" alt=""></div>
  <div class="item"><img src="photo.jpg" alt=""></div>
  ...
</div>
CSS
.items.is_end {
  justify-content: flex-end;
}

Space at the ends

The two carousels have align: 'center'. By default, a centered carousel stops at the edge at the first and the last slide, so that no empty space shows. This is containScroll: 'trimSnaps'.

With containScroll: false, the first and the last slide also go to the center, and empty space shows at the ends. With containScroll: 'keepSnaps', the carousel stops at the edges, but it keeps a snap for each slide. For this reason, it has 7 snaps, and some snaps at the ends have the same position.

containScroll: false: empty space at the ends containScroll: 'keepSnaps': no empty space, and a snap for each slide
HTML
<div class="items items_3 carousel" data-carousel='{"align":"center","containScroll":false}'>
  <div class="item"><img src="photo.jpg" alt=""></div>
  <div class="item"><img src="photo.jpg" alt=""></div>
  <div class="item"><img src="photo.jpg" alt=""></div>
  ...
</div>

<div class="items items_3 carousel" data-carousel='{"align":"center","containScroll":"keepSnaps"}'>
  <div class="item"><img src="photo.jpg" alt=""></div>
  <div class="item"><img src="photo.jpg" alt=""></div>
  <div class="item"><img src="photo.jpg" alt=""></div>
  ...
</div>

Several slides per snap

With slidesPerSnap: 'auto', one snap has all the slides that fit in the viewport. An arrow moves the carousel by a full page, and each dot is one page. A number, such as slidesPerSnap: 2, puts this number of slides into each snap.

HTML
<div class="items items_4 carousel" data-carousel='{"slidesPerSnap":"auto"}'>
  <div class="item"><img src="photo.jpg" alt=""></div>
  <div class="item"><img src="photo.jpg" alt=""></div>
  <div class="item"><img src="photo.jpg" alt=""></div>
  ...
</div>

Right to left

The parent of this carousel has dir="rtl". The library reads the direction from the CSS. The first slide is at the right, and a drag to the right shows the next slide. The arrows and the dots also follow the direction.

HTML
<div dir="rtl">
  <div class="items items_3 carousel" data-carousel='{"loop":true}'>
    <div class="item"><img src="photo.jpg" alt=""></div>
    <div class="item"><img src="photo.jpg" alt=""></div>
    <div class="item"><img src="photo.jpg" alt=""></div>
    ...
  </div>
</div>

To set the direction in the script, use dir: 'rtl'.

Fit mode

Each carousel here has fewer slides than the viewport can show. All slides fit, so the carousel does not move, and it does not show the arrows and the dots. The CSS alignment of the container applies: start, center and end.

HTML
<div class="items items_4 carousel">
  <div class="item">...</div>
  <div class="item">...</div>
</div>

When you add slides and they do not fit, the carousel starts to move. isFit() tells if all slides fit.

JavaScript
if (carousel.isFit()) {
  // All slides show, and the carousel does not move
}

Vertical carousel

The container has flex-direction: column, and the root has a height. For this reason, the carousel moves on the vertical axis.

HTML
<div class="items carousel items_vertical">
  <div class="item">...</div>
  <div class="item">...</div>
  <div class="item">...</div>
  ...
</div>
CSS
.demo_vertical .better {
  height: 420px;
}

.items_vertical {
  flex-direction: column;
}

.items_vertical .item {
  width: 100%;
  height: calc(100% / 3 - var(--gap-grid-y));
  margin-bottom: var(--gap-grid-y);
}

The mouse wheel and the trackpad move the carousel by their distance. When the wheel stops, the carousel goes to a snap. At the first and the last slide, the wheel scrolls the page. An element in a slide that can scroll, such as a long text, scrolls first.

JavaScript
// true: the wheel and the trackpad swipe move the carousel along its axis. 'both': all wheel motions move a horizontal carousel. false: off.
BetterCarousel(element, { wheel: true });

Responsive axis

This carousel is horizontal on a narrow screen and vertical from 769 px. Only the CSS changes. Change the width of the window to see the change.

HTML
<div class="items items_3 carousel items_switch is_center">
  <div class="item">...</div>
  <div class="item">...</div>
  <div class="item">...</div>
  ...
</div>
CSS
@media (min-width: 769px) {
  .demo_switch .better {
    height: 420px;
  }

  .items_switch {
    flex-direction: column;
  }

  .items_switch .item {
    width: 100%;
    height: calc(100% / 3 - var(--gap-grid-y));
  }
}

Responsive options

On a narrow screen, this is a carousel. From 769 px, a breakpoint sets active: false. The carousel stops, and the CSS shows the slides as a grid. Change the width of the window to see the change.

The options of a breakpoint merge over the other options. When a media query starts or stops to match, the carousel starts again with the new options, and the selected slide stays.

HTML
<div class="items items_3 carousel" data-carousel='{"breakpoints":{"(min-width: 769px)":{"active":false}}}'>
  <div class="item"><img src="photo.jpg" alt=""></div>
  <div class="item"><img src="photo.jpg" alt=""></div>
  <div class="item"><img src="photo.jpg" alt=""></div>
  ...
</div>
CSS
@media (min-width: 769px) {
  .items.carousel {
    flex-wrap: wrap;
  }
}

Variable widths

The slides have width: auto, so the content sets the width of each slide. In this example, the images load after 1 second and change the widths. The carousel measures again and keeps the selected slide.

HTML
<div class="items carousel items_auto" data-carousel='{"loop":true}'>
  <div class="item"><img src="logo.png" alt=""></div>
  <div class="item"><img src="logo.png" alt=""></div>
  <div class="item"><img src="logo.png" alt=""></div>
  ...
</div>
CSS
.items_auto .item {
  width: auto;
}

.items_auto img {
  height: 120px;
}

Variable and centered

The slides have width: auto, and the container has justify-content: center. With loop: true, the selected slide is always in the center, also at the first and the last slide. The images load after 1 second and change the widths. The carousel measures again and keeps the selected slide in the center.

HTML
<div class="items carousel items_auto is_center" data-carousel='{"loop":true}'>
  <div class="item"><img src="logo.png" alt=""></div>
  <div class="item"><img src="logo.png" alt=""></div>
  <div class="item"><img src="logo.png" alt=""></div>
  ...
</div>
CSS
.items_auto .item {
  width: auto;
}

.items_auto img {
  height: 120px;
}

.items.is_center {
  justify-content: center;
}

Growing selected slide

The selected slide gets the selected class, and a CSS transition makes it wider. The carousel keeps the selected slide in the center during the transition.

HTML
<div class="items carousel items_grow is_center" data-carousel='{"loop":true}'>
  <div class="item">...</div>
  <div class="item">...</div>
  <div class="item">...</div>
  ...
</div>
CSS
.items_grow .item {
  width: 160px;
  transition: width 0.3s;
}

.items_grow .item.selected {
  width: 320px;
}

Auto height

One slide shows in the viewport, and the photos have different shapes. With autoHeight: true, the viewport gets the height of the tallest slide in view. As a result, no empty space shows under a wide photo.

HTML
<div class="items items_1 carousel" data-carousel='{"autoHeight":true}'>
  <div class="item"><img src="photo.jpg" alt=""></div>
  <div class="item"><img src="photo.jpg" alt=""></div>
  <div class="item"><img src="photo.jpg" alt=""></div>
  ...
</div>

Add a transition to make the change of height smooth:

CSS
.better_auto_height .better_viewport {
  transition: height 0.3s;
}

Hidden at the start

The carousel is in the second tab, which is hidden at the start. A hidden carousel has no size, so it shows no arrows and no dots. When the tab shows, the ResizeObserver measures the carousel, and it starts to move. A call to reinit() is not necessary. The same applies to a carousel in an accordion or in a modal window.

Open the Photos tab. The carousel in it starts when the tab shows.

JavaScript
// Start the carousel at once, also when its tab is hidden
BetterCarousel(element);

// Later, show the tab: the carousel measures and starts to move
panel.hidden = false;
Loop

Infinite loop

With loop: true, the first slide comes after the last slide. This carousel has enough slides, so it needs no clones: the library moves the original slides.

HTML
<div class="items items_3 carousel" data-carousel='{"loop":true}'>
  <div class="item"><img src="photo.jpg" alt=""></div>
  <div class="item"><img src="photo.jpg" alt=""></div>
  <div class="item"><img src="photo.jpg" alt=""></div>
  ...
</div>

Centered loop

A loop with eight slides and four slides in the viewport. The selected slide is always in the center, also at the first and the last slide: the last slides show at the left of the first slide.

HTML
<div class="items items_4 carousel is_center" data-carousel='{"loop":true}'>
  <div class="item"><img src="photo.jpg" alt=""></div>
  <div class="item"><img src="photo.jpg" alt=""></div>
  <div class="item"><img src="photo.jpg" alt=""></div>
  ...
</div>

Loop with clones

Three slides, each 40% of the viewport. The loop needs more slides than this, so the library adds one copy of the slides. The clones are inert, they are hidden from screen readers, and they have no id attributes.

HTML
<div class="items carousel items_wide" data-carousel='{"loop":true}'>
  <div class="item"><img src="photo.jpg" alt=""></div>
  <div class="item"><img src="photo.jpg" alt=""></div>
  <div class="item"><img src="photo.jpg" alt=""></div>
  ...
</div>
CSS
.items_wide {
  --columns-count: 2.5;
}

The clones option controls the copies. 'auto' adds clones only if the loop needs them. false adds no clones: the loop moves only the original slides, so empty space can show if the slides are too few.

Clones fill the window

With clones: 'fill', the slides fill the full width of the window, also outside the viewport. The photo carousel at the top of this page uses this mode.

HTML
<div class="items items_3 carousel is_center" data-carousel='{"loop":true,"clones":"fill"}'>
  <div class="item"><img src="photo.jpg" alt=""></div>
  <div class="item"><img src="photo.jpg" alt=""></div>
  <div class="item"><img src="photo.jpg" alt=""></div>
  ...
</div>

Show the overflow of the viewport. Clip the section at the edges of the window, so that the page does not get wider:

CSS
.demo_fill {
  overflow: hidden;
}

.demo_fill .better {
  max-width: 600px;
  margin: 0 auto;
}

.demo_fill .better_viewport {
  overflow: visible;
}
Interaction

Free drag

With dragFree: true, the carousel glides after a drag and stops at any location.

The dragFriction option changes the length of the glide. Without dragFree, it changes how many snaps a fast flick moves.

dragFriction: 1, the default dragFriction: 3: the glide is 3 times shorter dragFriction: 0.5: the glide is 2 times longer
HTML
<div class="items items_4 carousel" data-carousel='{"loop":true,"dragFree":true}'>
  <div class="item"><img src="photo.jpg" alt=""></div>
  <div class="item"><img src="photo.jpg" alt=""></div>
  <div class="item"><img src="photo.jpg" alt=""></div>
  ...
</div>

<div class="items items_4 carousel" data-carousel='{"loop":true,"dragFree":true,"dragFriction":3}'>
  ...
</div>

<div class="items items_4 carousel" data-carousel='{"loop":true,"dragFree":true,"dragFriction":0.5}'>
  ...
</div>

Free drag with snaps

With dragFree: 'snap', the carousel glides after a drag and then stops at the nearest snap.

HTML
<div class="items items_4 carousel" data-carousel='{"loop":true,"dragFree":"snap"}'>
  <div class="item"><img src="photo.jpg" alt=""></div>
  <div class="item"><img src="photo.jpg" alt=""></div>
  <div class="item"><img src="photo.jpg" alt=""></div>
  ...
</div>

One snap per drag

With skipSnaps: false, a drag or a flick moves the carousel by one snap only. The snapOverdrag option sets how far a drag can go past the next snap, as a part of a snap. Past the next snap, the carousel moves at a quarter of the pointer speed. At the release, it goes back to the next snap.

snapOverdrag: 0.5, the default: a drag goes half a snap past the next snap snapOverdrag: 0: a drag stops at the next snap snapOverdrag: 5: past the next snap, a drag moves at a quarter of the pointer speed, almost with no limit
HTML
<div class="items items_4 carousel" data-carousel='{"loop":true,"skipSnaps":false}'>
  <div class="item"><img src="photo.jpg" alt=""></div>
  <div class="item"><img src="photo.jpg" alt=""></div>
  <div class="item"><img src="photo.jpg" alt=""></div>
  ...
</div>

<div class="items items_4 carousel" data-carousel='{"loop":true,"skipSnaps":false,"snapOverdrag":0}'>
  ...
</div>

<div class="items items_4 carousel" data-carousel='{"loop":true,"skipSnaps":false,"snapOverdrag":5}'>
  ...
</div>
JavaScript
// One snap for one drag, and a drag stops at the next snap
BetterCarousel(element, { skipSnaps: false, snapOverdrag: 0 });

Several snaps per drag

A number in skipSnaps sets the maximum number of snaps for one drag or flick. With the default true, a fast flick can move the carousel by more snaps.

skipSnaps: 2: a flick moves 2 snaps at most, and a drag goes half a snap past the second snap skipSnaps: 3, snapOverdrag: 0.25 and the loop: a flick moves 3 snaps at most
HTML
<div class="items items_4 carousel" data-carousel='{"skipSnaps":2}'>
  <div class="item"><img src="photo.jpg" alt=""></div>
  <div class="item"><img src="photo.jpg" alt=""></div>
  <div class="item"><img src="photo.jpg" alt=""></div>
  ...
</div>

<div class="items items_4 carousel" data-carousel='{"loop":true,"skipSnaps":3,"snapOverdrag":0.25}'>
  ...
</div>
JavaScript
// At most 2 snaps for one drag or flick
BetterCarousel(element, { skipSnaps: 2 });

Links in slides

Each slide is a link. A click opens the link, but a drag does not. Press Tab to move the focus to the next link. The carousel moves to show the focused slide.

HTML
<div class="items items_3 carousel">
  <a class="item" href="/product-1">...</a>
  <a class="item" href="/product-2">...</a>
  <a class="item" href="/product-3">...</a>
  ...
</div>

A drag starts after the pointer moves 10 px. Change this distance with dragThreshold.

Forms in slides

Each slide is an article with a link and a button. The second slide also has a form field. Press Tab to move the focus through the controls. The carousel moves to show each focused control.

HTML
<div class="items items_3 carousel">
  <article class="item">
    <h3>Card 1</h3>
    <p>A short text.</p>
    <a href="/card-1">Read more</a>
    <button type="button" aria-pressed="false">Like</button>
  </article>
  ...
</div>
  • A click on the field focuses it. A drag that starts on the field does not move the carousel.
  • A click on a button works. A drag that starts on a button moves the carousel, and it does not click the button.
  • Each article keeps its own role. The library adds aria-roledescription="slide" and a name such as "2 of 6".

Add and remove slides

The buttons add a slide at the end and remove the last slide. The carousel sees the change in the container and measures again. The selected slide stays. Then the carousel emits the slideschanged event. A call to reinit() is not necessary. With slideChanges: false, the carousel does not watch the container.

JavaScript
const carousel = BetterCarousel(element);

// Add a slide at the end
carousel.containerNode().append(slide);

// Remove the last slide
carousel.slideNodes().pop().remove();

carousel.on('slideschanged', () => {
  console.log(carousel.slideNodes().length + ' slides');
});
Navigation

Controls in a heading

With arrows: '.heading' and dots: '.heading', the library puts the arrows and the dots into the heading, outside the carousel. It searches for a selector in the root first, and then in each parent of the root. The value can also be an element.

New products

HTML
<section>
  <div class="heading">
    <h3>New products</h3>
  </div>
  <div class="items items_4 carousel" data-carousel='{"loop":true,"arrows":".heading","dots":".heading"}'>
    ...
  </div>
</section>

The library adds the arrows and then the dots at the end of the heading. Make the heading a flex row. Then use order to put the dots before the arrows:

CSS
.heading {
  display: flex;
  align-items: center;
  gap: 8px;
}

.heading h3 {
  flex: 1;
}

.heading .better_dots {
  order: 1;
  margin: 0;
}

.heading .better_button {
  order: 2;
  position: relative;
}

Dot styles

The dotsStyle option sets the style of the dots.

With dotsStyle: 'zoom', a window shows 5 dots, and the row of the dots slides in it to the selected dot. The dots at the ends are smaller. With many slides, the dots use a small space.

The default dotsStyle: 'glide' is the same zoom, and the marker of the selected dot stretches on its way. The window of the dots has the better_dots_glide class.

With dotsStyle: 'all', all dots show with the same size, and the selected dot has another color. The dots are directly in the window, which has the better_dots_all class.

dotsStyle: 'zoom': a window of 5 dots dotsStyle: 'glide', the default: the zoom, and the marker stretches dotsStyle: 'all': all dots with the same size
HTML
<div class="items items_4 carousel" data-carousel='{"loop":true,"dotsStyle":"zoom"}'>
  <div class="item"><img src="photo.jpg" alt=""></div>
  <div class="item"><img src="photo.jpg" alt=""></div>
  <div class="item"><img src="photo.jpg" alt=""></div>
  ...
</div>

<div class="items items_4 carousel" data-carousel='{"loop":true}'>
  ...
</div>

<div class="items items_4 carousel" data-carousel='{"loop":true,"dotsStyle":"all"}'>
  ...
</div>

Custom controls

With arrows: false and dots: false, the library adds no controls, and the page can have its own. In this example, the buttons and the counter use the methods and the events of the carousel:

  • canGoToPrev() and canGoToNext() disable a button at the ends;
  • the select event updates the counter, and the init and reinit events write its first value.
HTML
<div class="items items_3 carousel" data-carousel='{"arrows":false,"dots":false}'>...</div>
<div class="controls">
  <button type="button" class="prev">Previous</button>
  <span class="counter" aria-live="polite"></span>
  <button type="button" class="next">Next</button>
</div>
JavaScript
const carousel = BetterCarousel(element),
  prev = document.querySelector('.prev'),
  next = document.querySelector('.next'),
  counter = document.querySelector('.counter');

function update() {
  prev.disabled = !carousel.canGoToPrev();
  next.disabled = !carousel.canGoToNext();
  counter.textContent = (carousel.selectedSnap() + 1) + ' / ' + carousel.snapProgress().length;
}

prev.addEventListener('click', () => carousel.goToPrev());
next.addEventListener('click', () => carousel.goToNext());
['init', 'reinit', 'resize', 'select'].forEach((name) => carousel.on(name, update));

Thumbnails

A main gallery with a row of thumbnails under it. The arrows of the main gallery are at the two sides of the thumbnails. The thumbnails carousel has the sync option: it follows the main gallery, and a click on a thumbnail selects its photo.

Markup

Put the same slides into the two carousels, in the same order. Use buttons for the thumbnails, so that the keyboard can select them.

HTML
<div class="items items_1 carousel gallery_main" data-carousel='{"dots":false,"arrows":".gallery_nav"}'>
  <div class="item"><img src="photo-1.jpg" alt="Photo 1"></div>
  <div class="item"><img src="photo-2.jpg" alt="Photo 2"></div>
  ...
</div>

<div class="gallery_nav">
  <div class="items carousel is_center gallery_thumbs" data-carousel='{"sync":".gallery_main","arrows":false,"dots":false}'>
    <button type="button" class="item"><img src="thumb-1.jpg" alt="Show photo 1"></button>
    <button type="button" class="item"><img src="thumb-2.jpg" alt="Show photo 2"></button>
    ...
  </div>
</div>

The arrows option of the main gallery puts its arrows into .gallery_nav. The CSS puts them at the two sides of the thumbnails. The thumbnail of the selected photo gets the selected class:

CSS
.gallery_nav {
  position: relative;
  padding: 0 3.25rem;
}

.gallery_nav .better_button {
  top: 0;
  height: auto;
}

.gallery_thumbs .item {
  width: 20%; /* 5 thumbnails. In a centered row, an odd number shows only whole thumbnails. */
  opacity: 0.6;
  transition: opacity 0.2s;
}

.gallery_thumbs .item.selected {
  opacity: 1;
  outline: 3px solid var(--button-base);
  outline-offset: -3px;
}

JavaScript

The value of sync can be a selector, a container or a carousel. The library searches for a selector in the root of the carousel first, and then in each parent of the root.

JavaScript
const main = BetterCarousel(document.querySelector('.gallery_main'), { dots: false, arrows: '.gallery_nav' });

const thumbs = BetterCarousel(document.querySelector('.gallery_thumbs'), {
  sync: main,
  arrows: false,
  dots: false,
  dragFree: 'snap'
});

How the link works

  • Only a click on a thumbnail selects a photo. A drag moves the thumbnails only: the photo and the marked thumbnail stay.
  • A swipe, an arrow, a dot, the autoplay or a goToSnap() call on the main gallery moves the thumbnails to the thumbnail of the photo.
  • The selectedSlide() method of the thumbnails gives the slide of the main gallery, also after a drag on the thumbnails.
  • The two carousels can start in any order. The link starts when the two carousels are ready.
  • The two carousels can have different options: for example, a vertical row of thumbnails, or loop on the main gallery.
  • A carousel can follow one other carousel only.

More photos in view

If the main gallery shows more than one photo, mark all their thumbnails with the slidesinview event:

JavaScript
main.on('slidesinview', () => {
  const list = main.slidesInView();
  thumbs.slideNodes().forEach((node, index) => node.classList.toggle('in_view', list.includes(index)));
});

Motion duration

The duration option sets the time of a motion by one snap, in ms. It applies to the arrows, the dots, the arrow keys, the autoplay and goToSnap(). A motion by more snaps takes more time, to a maximum of 2 times this value.

The auto scroll has its own speed in px/s. The Auto scroll section shows it.

duration: 500, the default duration: 800: a slower motion
HTML
<div class="items items_4 carousel" data-carousel='{"loop":true}'>
  <div class="item"><img src="photo.jpg" alt=""></div>
  <div class="item"><img src="photo.jpg" alt=""></div>
  <div class="item"><img src="photo.jpg" alt=""></div>
  ...
</div>

<div class="items items_4 carousel" data-carousel='{"loop":true,"duration":800}'>
  ...
</div>
Autoplay

Autoplay

The carousel goes to the next slide each 2 seconds, and the bar over the slides shows the time to the next slide. Slide 3 stays for 6 seconds, because it has data-delay="6000". The button stops and starts the autoplay.

HTML
<div class="bar"></div>
<div class="items items_3 carousel">
  <div class="item">...</div>
  <div class="item">...</div>
  <div class="item" data-delay="6000">...</div>
  ...
</div>
JavaScript
const bar = document.querySelector('.bar');

BetterCarousel(element, {
  loop: true,
  autoplay: {
    delay: 2000,
    timer: (delay) => {
      const animation = bar.animate([{ scale: '0 1' }, { scale: '1 1' }], delay);
      return () => animation.cancel();
    }
  }
});
CSS
.bar {
  height: 4px;
  background: currentColor;
  transform-origin: left;
  scale: 0 1;
}

The timer function shows the time to the next slide. The carousel calls it when the timer starts, with the delay in ms and the carousel. The function can return a cleanup function. The carousel calls the cleanup function when this timer ends or stops, for example at a pause or a drag. The library has no styles for a timer. An animation of scale, translate or opacity runs on the compositor, so no script runs for each frame.

The autoplay pauses when the keyboard focus is in the carousel, when the tab is hidden, and when the carousel is out of view. If the user prefers reduced motion, the autoplay does not start. A breakpoint change keeps the play state: a stopped autoplay stays stopped. A number sets the delay, and an object changes the other settings. In the object, delay can also be an array with one delay for each snap. A data-delay attribute has priority over delay. These are the default values:

JavaScript
BetterCarousel(element, {
  autoplay: {
    delay: 4000,               // ms on each slide, or an array with ms for each snap
    stopOnInteraction: true,   // A drag, an arrow or a dot stops the autoplay
    pauseOnHover: false,   // Pause while the mouse is on the carousel
    pauseOnFocus: true,       // Pause while the keyboard focus is in the carousel
    stopOnLastSnap: false,     // Stop at the last snap, if loop is false
    playOnInit: true,
    instant: false,            // Jump to the next slide with no motion
    timer: null                // A function that shows the time to the next slide
  }
});

Auto scroll

Five logos move at a constant speed of 60 px/s. The motion runs on the compositor: no script runs for each frame. The logos are too few to fill the strip, so the library adds clones. The motion pauses while the mouse is on the strip.

HTML
<div class="items carousel items_logos" data-carousel='{"loop":true,"dots":false,"arrows":false,"autoScroll":{"speed":60,"pauseOnHover":true}}'>
  <div class="item"><img src="logo.svg" alt="Company"></div>
  <div class="item"><img src="logo.svg" alt="Company"></div>
  <div class="item"><img src="logo.svg" alt="Company"></div>
  ...
</div>

These are the default values:

JavaScript
BetterCarousel(element, {
  autoScroll: {
    speed: 120,                // px per second
    direction: 'next',         // or 'prev'
    startDelay: 1000,          // ms before the start, and after an interaction
    stopOnInteraction: true,
    pauseOnHover: false,
    pauseOnFocus: true,
    playOnInit: true
  }
});
Effects

Progress bar

The progress and offset options give the position of the carousel to CSS or to a function, on each frame of a motion. They are off by default, because a script runs on each frame while they are on.

With progress: true, the root gets the --better-progress variable, from 0 to 1. In this example, it sets the width of the bar above the slides.

HTML
<div class="items items_3 carousel" data-carousel='{"progress":true}'">
  <div class="item"><img src="photo.jpg" alt=""></div>
  <div class="item"><img src="photo.jpg" alt=""></div>
  <div class="item"><img src="photo.jpg" alt=""></div>
  ...
</div>
CSS
.better::before {
  content: "";
  display: block;
  height: 4px;
  margin-bottom: 12px;
  background: currentColor;
  transform-origin: left;
  scale: var(--better-progress, 0) 1;
}

Parallax

With offset: true, each slide gets the --better-offset variable: the distance from its snap position, in slides. It is 0 for the selected slide, 1 for the next slide and -1 for the previous slide.

In this example, each photo is larger than its slide, and it moves slower than the slide. clamp() keeps the shift in the range from -1 to 1.

HTML
<div class="items items_1 carousel" data-carousel='{"loop":true,"offset":true}'">
  <div class="item"><img src="photo.jpg" alt=""></div>
  <div class="item"><img src="photo.jpg" alt=""></div>
  <div class="item"><img src="photo.jpg" alt=""></div>
  ...
</div>
CSS
.better .item {
  overflow: hidden;
}

.better .item img {
  scale: 1.3;
  translate: calc(clamp(-1, var(--better-offset, 0), 1) * -10%) 0;
}

Scale and fade

The photos far from the center are smaller and lighter. max(x, -1 * x) gives the distance in slides on the two sides of the center.

Change the photo in the slide, not the slide. The carousel measures the slides, and a scale on a slide changes its size for the carousel.

HTML
<div class="items items_3 carousel" data-carousel='{"loop":true,"align":"center","offset":true}'">
  <div class="item"><img src="photo.jpg" alt=""></div>
  <div class="item"><img src="photo.jpg" alt=""></div>
  <div class="item"><img src="photo.jpg" alt=""></div>
  ...
</div>
CSS
.better .item {
  --distance: min(1, max(var(--better-offset, 0), -1 * var(--better-offset, 0)));
}

.better .item img {
  scale: calc(1 - 0.25 * var(--distance));
  opacity: calc(1 - 0.6 * var(--distance));
}

Custom effects

A function in place of true gets the values that CSS cannot calculate. In this example:

  • the progress function writes the position between the snaps, for example 2.4, and the progress in percent;
  • the offset function sets the opacity from visible, the part of the slide in the viewport. The slides at the edges are lighter.

The carousel uses the same state object for each call, so read the values during the call.

JavaScript
const counter = document.querySelector('.counter');

BetterCarousel(element, {
  loop: true,
  align: 'center',
  progress: ({ progress, snap }) => {
    counter.textContent = 'Snap ' + (snap + 1).toFixed(1) + ', ' + Math.round(progress * 100) + '%';
  },
  offset: ({ node, visible }) => {
    node.style.opacity = 0.3 + 0.7 * visible;
  }
});

The other values of the offset state are index, offset, distance (the offset in px) and size (the slide size in px).

Reference

Options

All options, their types and their default values.

OptionTypeDefaultDescription
axis'x', 'y', 'auto''auto'The axis of the motion. With 'auto', the CSS of the container sets the axis. (example)
align'start', 'center', 'end', 'auto', function'auto'The position of the selected snap in the viewport. A function gets (viewSize, snapSize, index) and returns the offset in px. With 'auto', justify-content sets the alignment. (example)
dir'ltr', 'rtl', 'auto''auto'The text direction. With 'auto', the CSS direction sets it. (example)
loopbooleanfalseThe first slide comes after the last slide. (example)
clones'auto', 'fill', false'auto''auto': add clones only if the loop needs them. 'fill': add clones that fill the window. false: add no clones. (example)
dragFreeboolean, 'snap'falsetrue: glide after a drag and stop at any position. 'snap': glide and stop at the nearest snap. (example)
dragFrictionnumber1The length of the glide after a fast drag: the glide distance is divided by this number. 2: half the distance. 0.5: 2 times the distance. It also changes how many snaps a flick moves. The value must be more than 0. (example)
containScroll'trimSnaps', 'keepSnaps', false'trimSnaps''trimSnaps': no empty space at the ends. 'keepSnaps': no empty space, but keep a snap for each group. false: snaps can show empty space. (example)
slidesPerSnapnumber, 'auto'1The number of slides in one snap. 'auto': the slides that fit in the viewport. (example)
skipSnapsboolean, numbertrueThe maximum number of snaps for one drag or flick. true: no limit, and a fast flick can move more than one snap. false: one snap. A number: this number of snaps. A drag can go past the limit by snapOverdrag. (example)
snapOverdragnumber0.5The maximum distance that a drag can go past the skipSnaps limit, as a part of a snap. Past the limit, the carousel moves at a quarter of the pointer speed. 0: the drag stops at the limit. (example)
dragThresholdnumber10The distance in px that the pointer moves before a drag starts.
durationnumber500The duration of a motion by one snap, in ms. A longer motion takes more time, to a maximum of 2 times this value. (example)
startSnapnumber0The index of the snap at the start. (example)
lazyboolean, numberfalsetrue: start when the carousel comes within one screen of the view. A number: the distance in px. (example)
dragbooleantrueDrag with the mouse, the pen and the finger. A press during a motion stops the motion. A press on a form field does not start a drag. To keep the drag off another element, such as a map in a slide, stop the propagation of its pointerdown event. An element in a slide that can scroll does not keep a touch move along the axis. To let it scroll along the axis, such as a wide table, give it touch-action: auto.
wheelboolean, 'both'trueThe wheel moves the carousel along its axis. A vertical wheel motion moves a vertical carousel. A horizontal wheel motion, such as a trackpad swipe, moves a horizontal carousel, and a vertical wheel motion scrolls the page. 'both': all wheel motions move a horizontal carousel. false: the wheel does not move the carousel. In nested carousels, the inner carousel gets the wheel first. (example)
keysbooleantrueThe arrow keys move the carousel while the keyboard focus is in it: left and right in a horizontal carousel, up and down in a vertical carousel. A key in a form field does not move the carousel. In nested carousels, the inner carousel gets the key first.
resizebooleantrueMeasure again when a size changes. (example)
slideChangesbooleantrueMeasure again when the page adds or removes a slide. (example)
focusbooleantrueGo to a slide when it gets the keyboard focus. (example)
inViewThresholdnumber0The part of a slide, from 0 to 1, that must show for slidesInView(). (example)
activebooleantruefalse: do not start the carousel. Use it in breakpoints. (example)
breakpointsobject{}The options for media queries: { '(min-width: 768px)': { loop: true } }. (example)
containerstringnullThe selector of the container, if the element is the root.
slidesstringnullThe selector of the slides. With null, all children of the container are slides.
wrapperbooleantrueAdd the root and the viewport if the page does not have them. (example)
arrowsboolean, Element, stringtrueAdd the arrows to the root. false: no arrows. An element or a selector: add the arrows to that element. (example)
dotsboolean, Element, stringtrueAdd the dots. The values are the same as for arrows. (example)
dotsStyle'zoom', 'glide', 'all''glide'The style of the dots. 'zoom': a window of 5 dots that slides, with smaller dots at the ends. 'glide': the zoom, and the marker of the selected dot stretches on its way. 'all': all dots with the same size, and the selected dot has another color. (example)
labelsobjectEnglishThe texts for screen readers: carousel, slide ('%d of %n'), prev, next, dot ('Go to slide %d'), play, pause. %d is the slide number, and %n is the number of slides. An empty text adds no name. (example)
classesstring, objectnullA class prefix such as 'embla', or an object with the names to change. The Classes table gives all names. (example)
statestring''The prefix of the state classes, such as 'is_'. (example)
synccarousel, Element, stringnullAnother carousel, its container or a selector. This carousel follows the selected slide of the other carousel. A click on a slide selects it in the other carousel. (example)
autoplayboolean, number, objectfalseGo to the next slide after a delay. true, a delay in ms, or an object. (example)
autoScrollboolean, number, objectfalseMove the slides at a constant speed. true, a speed in px/s, or an object. (example)
autoHeightbooleanfalseThe viewport gets the height of the tallest slide in view. During a motion or a drag, the slides in view at the selected snap set the height. The height transition has the duration and the curve of a motion: the carousel sets the duration option as --better-duration on the root. (example)
progressboolean, functionfalseFollow the progress, from 0 to 1. true sets --better-progress on the root. A function gets { progress, snap } on each frame of a motion. See Progress and offset.
offsetboolean, functionfalseFollow the distance of each slide from its snap position, in slides. true sets --better-offset on each slide. A function gets { node, index, offset, distance, size, visible } for each slide on each frame of a motion.

Methods

BetterCarousel(element, options) returns the carousel. The table gives the methods of the carousel, and of the BetterCarousel function.

MethodReturnsDescription
BetterCarousel(element, options)carouselStart a carousel on a container or on its viewport. If the element has a carousel, return that carousel.
goToSnap(index, instant)-Go to a snap. index is a snap index. With instant set to true, jump with no motion.
goToNext(instant), goToPrev(instant)-Go to the next or the previous snap.
goToSlide(index, instant)-Go to the snap that shows a slide. index is a slide index. This slide becomes the selected slide.
canGoToNext(), canGoToPrev()booleantrue if a next or a previous snap exists. In a loop, true if not all slides fit.
selectedSnap(), previousSnap()numberThe index of the selected snap, or of the snap before it.
selectedSlide()numberThe index of the selected slide. With sync, the slide that is selected in the other carousel.
snapOfSlide(index)numberThe index of the snap that shows a slide.
snapProgress()number[]The progress of each snap, from 0 to 1.
progress()numberThe progress now, from 0 to 1, also during a motion.
slidesInView()number[]The indexes of the slides in view.
slideNodes()HTMLElement[]The slides. The list does not include the clones.
rootNode(), viewportNode(), containerNode()HTMLElementThe root, the viewport and the container.
isFit()booleantrue if all slides fit in the viewport.
options()objectThe options that apply now, after the breakpoints.
reinit(options)-Merge new options and start again. The selected slide stays.
destroy()-Stop the carousel and restore the markup.
on(name, handler), off(name, handler)carouselAdd or remove an event handler. The handler gets (carousel, name).
autoplayobjectOnly with the autoplay option: play(), stop(), reset() and isPlaying().
autoScrollobjectOnly with the autoScroll option: play(), stop() and isPlaying().
BetterCarousel.get(element)carousel, undefinedThe carousel of a root, a viewport or a container.
BetterCarousel.initAll(selector, options)carousel[]Start a carousel on each element that matches the selector.
BetterCarousel.defaultsobjectThe options for all carousels. Set it before you start the carousels.
JavaScript
const carousel = BetterCarousel(element, { loop: true });

carousel.on('select', (carousel) => {
  console.log('Slide', carousel.selectedSlide());
});

document.querySelector('.next').addEventListener('click', () => carousel.goToNext());

Events

Add a handler with on(name, handler), and remove it with off(name, handler). The handler gets (carousel, name).

EventWhen
initThe carousel measured the layout for the first time.
reinitA reinit() call or a breakpoint started the carousel again.
resizeThe layout changed.
selectThe selected snap changed.
scrollThe position changed during a motion or a drag.
settleA motion stopped.
dragstart, dragendA drag started or stopped.
slidesinviewThe slides in view changed.
slideschangedThe page added, removed or replaced a slide.
slidefocusA slide got the keyboard focus.
autoplay:play, autoplay:stopThe autoplay started or stopped.
autoscroll:play, autoscroll:stopThe auto scroll started or stopped.
destroyThe carousel stopped and restored the markup.

CAUTION: Add a scroll handler only if you need it. With this handler, each motion runs in a requestAnimationFrame loop on the main thread.

Classes

The default class names. A prefix in classes changes the first part of the names. The state prefix changes the state classes: selected, dragging, playing and the classes of the dots.

ClassElement
betterThe root
better_viewportThe viewport
better_containerThe container
better_horizontal, better_verticalThe axis, on the root
better_fitOn the root, if all slides fit
better_auto_heightOn the root, with autoHeight
better_button, better_prev, better_next, better_playThe buttons
better_dots, better_dotThe window of the dots, and the dots
better_dots_track, better_dots_markerWith dotsStyle: 'zoom' and 'glide': the row of the dots that slides in the window, and the marker of the selected dot
better_dots_glide, better_dots_allOn the window of the dots, with dotsStyle: 'glide' and 'all'
selectedThe selected slide
cloneA clone of a slide
draggingOn the root, during a drag
playingOn the root, while the autoplay or the auto scroll plays
current, prev, next, first, lastThe selected dot and the four dots around it. With dotsStyle: 'all', only current.
JavaScript
// .embla, .embla_viewport, .embla_button, .is_selected
BetterCarousel(element, { classes: 'embla', state: 'is_' });

// Change one name
BetterCarousel(element, { classes: { selected: 'snapped' } });

Custom class names

With classes: 'embla', the class names get the prefix embla: embla, embla_viewport, embla_button. With state: 'is_', the state classes get the prefix is_: is_selected, is_current, is_dragging. Use the prefixes to match the styles of an existing theme. This carousel has many snaps, so the dots show a window of five dots around the selected dot.

HTML
<div class="items items_4 carousel" data-carousel='{"classes":"embla","state":"is_","loop":true}'>
  <div class="item"><img src="photo.jpg" alt=""></div>
  <div class="item"><img src="photo.jpg" alt=""></div>
  <div class="item"><img src="photo.jpg" alt=""></div>
  ...
</div>

Compile the SCSS file with $better: 'embla' and $better-state: 'is_'. The Styling section shows how.

Migrate from Embla

This table gives the names and the behavior that are different from Embla 9 and Embla 8. The other options, methods and events have the same names as in Embla.

EmblaEmbla nameBetter Carousel
9Handler (api, event)Handler (carousel, name). The events have no detail.
9Autoplay delay as a function that gives one delay for each snapAutoplay delay as an array with one delay for each snap
8Option startIndexstartSnap
8Options watchDrag, watchResize, watchSlides, watchFocusdrag, resize, slideChanges, focus
9Option draggabledrag
8, 9Options slidesToScroll, directionslidesPerSnap, dir
8, 9Autoplay and AutoScroll stopOnMouseEnter, stopOnFocusInpauseOnHover, pauseOnFocus
8, 9AutoScroll direction: 'forward', 'backward'direction: 'next', 'prev'
8Autoplay jumpinstant
8scrollTo(index, jump)goToSnap(index, instant)
9goTo(index, instant)goToSnap(index, instant)
8scrollNext(), scrollPrev()goToNext(), goToPrev()
8canScrollNext(), canScrollPrev()canGoToNext(), canGoToPrev()
8selectedScrollSnap(), previousScrollSnap()selectedSnap(), previousSnap()
8scrollSnapList()snapProgress()
9snapList()snapProgress()
8, 9scrollProgress(), reInit()progress(), reinit()
8Events reInit, slidesInView, slidesChanged, slideFocusreinit, slidesinview, slideschanged, slidefocus
8Events pointerDown, pointerUpdragstart, dragend
9Events pointerdown, pointerupdragstart, dragend
8, 9Plugins Autoplay, AutoScroll, AutoHeightThe options autoplay, autoScroll, autoHeight
8, 9plugins().autoplay, plugins().autoScrollcarousel.autoplay, carousel.autoScroll
8, 9Plugin ClassNamesThe options classes and state
8, 9Plugin WheelGestures (a separate package)The option wheel
Accessibility and speed

Accessibility

The carousel follows the carousel pattern of the WAI-ARIA Authoring Practices and WCAG 2.1 AA.

  • The root is a region with the name "Carousel". Each slide has a name such as "2 of 8". A slide that is an article or a list item keeps its own role.
  • The arrows and the dots are buttons with names. A screen reader reads each new slide (aria-live), but not during the autoplay.
  • Tab moves the focus through the links and the fields in the slides. The carousel moves to show the focused element.
  • Clones are inert and hidden from screen readers. A click on a link or a button in a clone goes to the same element in its slide. The form fields in clones have no name, so the form sends only the fields of the slides.
  • The autoplay and the auto scroll have a play and pause button (WCAG 2.2.2). The keyboard focus pauses them. If the user prefers reduced motion, they do not start.
  • A drag across the axis scrolls the page. A link opens on a click, but not after a drag or after a press that stopped a motion.

To translate the labels, set labels. In the texts, %d is the slide number, and %n is the number of slides:

JavaScript
BetterCarousel.defaults = {
  labels: {
    carousel: 'Karussell',
    slide: '%d von %n',
    prev: 'Vorheriges Bild',
    next: 'Nächstes Bild',
    dot: 'Zu Bild %d',
    play: 'Diashow starten',
    pause: 'Diashow anhalten',
  },
};

Performance

The library is made for slow phones. A motion runs on the compositor, and a carousel at rest uses no CPU.

  • A motion is a Web Animations API animation of translate. No script runs for each frame.
  • The auto scroll is one animation that does not stop. During the motion, the browser does no script, style, layout or paint work.
  • One ResizeObserver serves all carousels. It reads the layout of all carousels first, and then it writes. For this reason, the browser calculates the layout only one time.
  • Only two elements of the dots animate: the row of the dots and the marker of the selected dot. Both move with translate. A click on a dot causes no layout work.
  • The listeners for the autoplay and the mouse wheel exist only while they can do something.
  • The progress and offset options run a script on each frame of a motion. For this reason, they are off by default.
FileMinifiedGzipBrotli
better-carousel.min.js32.3 KB13.3 KB12.1 KB
better-carousel.css5.1 KB1.5 KB1.2 KB
Total37.4 KB14.8 KB13.4 KB

The benchmark compares Better Carousel with Swiper, Embla Carousel and Glide in Chrome, on a phone with a CPU 4 times slower. Less is better.

MeasureBetterSwiperEmblaGlide
6 slide changes, main-thread ms118128866197
5 drags, main-thread ms5196191477816
Autoplay, CPU %0.616.716.91.6
Dropped or late frames on a busy page, %1.93.015.50.7
Total Blocking Time, 10 carousels, ms41654254
All features, JS and CSS, KB gzip15.032.913.7not available

The README gives the method, the desktop values and the feature list.

Lazy start

With lazy: true, a carousel out of view waits until it comes within one screen of the view. This decreases the script time and the layout work at page load. A number sets the distance in px.

JavaScript
BetterCarousel.initAll('.items.carousel', { lazy: true });

// Start within 300 px of the view
BetterCarousel.initAll('.items.carousel', { lazy: 300 });
  • A carousel near the screen starts at once, so that its arrows and dots do not move the page after the first paint.
  • Before the start, BetterCarousel.get() gives the carousel, but rootNode() is undefined and slideNodes() is empty.
  • A goToSnap() call starts the carousel at once.

CAUTION: Clip the slides of a waiting carousel with CSS, for example with overflow-x: clip on a parent. If you do not, the page gets wider than the screen, and a phone shows the page smaller.

Lazy images

Each image has the native loading="lazy" attribute. The browser loads an image when its slide comes near the view, also if the slide is out of the viewport of the carousel. Chrome and Firefox load the images of the next slides before they show. This needs no script.

HTML
<div class="items items_3 carousel">
  <div class="item"><img src="photo.jpg" alt="" loading="lazy"></div>
  <div class="item"><img src="photo.jpg" alt="" loading="lazy"></div>
  ...
</div>