Card 1
A short text.
Read more about card 1A 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.









No special classes or markup. Your CSS sets the layout.
The browser animates the slides, not JavaScript.
13.3 KB gzip with all features.
WCAG 2.1 AA, with keyboard and screen reader support.
Better Carousel is one JavaScript file and one stylesheet. It has no dependencies.
Add the stylesheet and the script to the page. The script adds the global BetterCarousel function. This page uses the library in this way.
<link rel="stylesheet" href="dist/better-carousel.css">
<script src="dist/better-carousel.min.js"></script>Install the package. Then import the script and the stylesheet.
npm install @twistedandy/better-carouselimport BetterCarousel from '@twistedandy/better-carousel';
import '@twistedandy/better-carousel/css';| File | Format | Use |
|---|---|---|
dist/better-carousel.min.js | IIFE, minified | For a script tag. It adds the global BetterCarousel function. |
dist/better-carousel.js | ES module | For a bundler: import BetterCarousel from '@twistedandy/better-carousel'. |
dist/better-carousel.css | CSS | The styles with the default class names. |
src/types/better-carousel.d.ts | TypeScript | The types. TypeScript and the editors find them automatically. |
src/styles/better-carousel.scss | SCSS | The styles with your class names (see Styling). |
A carousel is a container with slides. Your CSS gives the container a row layout, and the library moves the container.
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.
<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:
/* 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:
/* 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.
// 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.
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.
flex-wrap: nowrap. Set flex: none on the cards, so that they do not shrink.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)./* 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;
}/* 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.
The library puts the container into a viewport and a root. Then it adds the arrows and the dots to the root:
<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>| Term | Meaning |
|---|---|
| Root | The outer element. It holds the viewport, the arrows and the dots. The library adds it if the page does not have it. |
| Viewport | The element that clips the slides. Its size is the visible area. |
| Container | The element that moves. Your CSS sets its layout, and the library sets its translate. |
| Slide | A child of the container, or an element that matches the slides selector. |
| Snap | A position where the carousel can stop. A snap shows one slide or a group of slides. |
| Selected snap | The snap that shows now. selectedSnap() gives its index. |
| Selected slide | The slide at the selected snap. It gets the selected class. selectedSlide() gives its index. |
| Clone | A 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. |
| Motion | A change of position with an animation. When a motion stops, the settle event occurs. |
| Fit | All 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.
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 container | The result |
|---|---|
display: flex, a row | A horizontal carousel |
flex-direction: column | A vertical carousel (example) |
display: grid with grid-auto-flow: column | A horizontal carousel with more rows (example) |
justify-content: center | The selected slide is in the center (example) |
justify-content: flex-end | The selected slide is at the end (example) |
gap, column-gap or row-gap | The 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 container | The same, for a layout without gap. The library adds the margins to the gap. |
direction: rtl | A right-to-left carousel |
| The padding of the viewport | The 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.
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.
// 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:
<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:
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.
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.
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.
: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;
}The SCSS file uses @import and global variables, so it compiles with Dart Sass and with node-sass. Set the variables before the import:
// 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.
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.
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.
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>
</>
);
}Start the carousel in onMounted. Destroy it in onBeforeUnmount.
<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>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().
<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>Start the carousel in onMount. Destroy it with onCleanup.
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>
);
}arrows and dots options.reinit(newOptions). The selected slide stays.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.
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.
1
2
3
4
5
6
7
8<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>BetterCarousel.initAll('.items.carousel');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.
1
2
3
4
5
6
7
8<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>.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.
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.
1
2
3
4
5
6
7
8<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>.items.is_end {
justify-content: flex-end;
}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
1
2
3
4
5
6
7containScroll: 'keepSnaps': no empty space, and a snap for each slide
1
2
3
4
5
6
7<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>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.
1
2
3
4
5
6
7
8
9
10
11
12<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>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.
1
2
3
4
5
6
7<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'.
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.
1
2
1
2
1
2<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.
if (carousel.isFit()) {
// All slides show, and the carousel does not move
}The container has flex-direction: column, and the root has a height. For this reason, the carousel moves on the vertical axis.
<div class="items carousel items_vertical">
<div class="item">...</div>
<div class="item">...</div>
<div class="item">...</div>
...
</div>.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.
// 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 });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.
<div class="items items_3 carousel items_switch is_center">
<div class="item">...</div>
<div class="item">...</div>
<div class="item">...</div>
...
</div>@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));
}
}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.
1
2
3
4
5
6<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>@media (min-width: 769px) {
.items.carousel {
flex-wrap: wrap;
}
}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.
<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>.items_auto .item {
width: auto;
}
.items_auto img {
height: 120px;
}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.
<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>.items_auto .item {
width: auto;
}
.items_auto img {
height: 120px;
}
.items.is_center {
justify-content: center;
}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.
<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>.items_grow .item {
width: 160px;
transition: width 0.3s;
}
.items_grow .item.selected {
width: 320px;
}A CSS grid with two rows and loop: true. The first slide and the sixth slide of each group of ten use 2 × 2 cells. The library reads the columns of the grid.




















<div class="items items_grid_large 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>.items_grid_large {
display: grid;
grid-template-rows: repeat(2, 1fr);
grid-auto-flow: column dense;
grid-auto-columns: 25%;
}
/* The margins of the slides make the space, as in a flex row */
.items_grid_large .item {
width: calc(100% - 10px);
margin: 0 10px 10px 0;
}
.items_grid_large .item:nth-child(10n + 1),
.items_grid_large .item:nth-child(10n + 6) {
grid-column: auto / span 2;
grid-row: auto / span 2;
}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.
1
2
3
4
5
6<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:
.better_auto_height .better_viewport {
transition: height 0.3s;
}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.
1
2
3
4
5
6
7
8
9
10<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>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.
1
2
3
4
5
6
7
8<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>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.
1
2
3<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>.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.
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.
1
2
3
4
5<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:
.demo_fill {
overflow: hidden;
}
.demo_fill .better {
max-width: 600px;
margin: 0 auto;
}
.demo_fill .better_viewport {
overflow: visible;
}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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20dragFriction: 3: the glide is 3 times shorter
1
2
3
4
5
6
7
8
9
10
11
12dragFriction: 0.5: the glide is 2 times longer
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20<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>With dragFree: 'snap', the carousel glides after a drag and then stops at the nearest snap.
1
2
3
4
5
6
7
8
9
10
11
12<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>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
1
2
3
4
5
6
7
8
9
10
11
12snapOverdrag: 0: a drag stops at the next snap
1
2
3
4
5
6
7
8
9
10
11
12snapOverdrag: 5: past the next snap, a drag moves at a quarter of the pointer speed, almost with no limit
1
2
3
4
5
6
7
8
9
10
11
12<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>// One snap for one drag, and a drag stops at the next snap
BetterCarousel(element, { skipSnaps: false, snapOverdrag: 0 });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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16skipSnaps: 3, snapOverdrag: 0.25 and the loop: a flick moves 3 snaps at most
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16<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>// At most 2 snaps for one drag or flick
BetterCarousel(element, { skipSnaps: 2 });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.
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.
A short text.
Read more about card 1A short text.
Read more about card 2A short text.
Read more about card 3A short text.
Read more about card 4A short text.
Read more about card 5A short text.
Read more about card 6<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>article keeps its own role. The library adds aria-roledescription="slide" and a name such as "2 of 6".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.
1
2
3
4const 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');
});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.
1
2
3
4
5
6
7
8<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:
.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;
}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
1
2
3
4
5
6
7
8
9
10dotsStyle: 'glide', the default: the zoom, and the marker stretches
1
2
3
4
5
6
7
8
9
10dotsStyle: 'all': all dots with the same size
1
2
3
4
5
6
7
8
9
10<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>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;select event updates the counter, and the init and reinit events write its first value.
1
2
3
4
5
6
7<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>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));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.









Put the same slides into the two carousels, in the same order. Use buttons for the thumbnails, so that the keyboard can select them.
<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:
.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;
}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.
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'
});goToSnap() call on the main gallery moves the thumbnails to the thumbnail of the photo.selectedSlide() method of the thumbnails gives the slide of the main gallery, also after a drag on the thumbnails.loop on the main gallery.If the main gallery shows more than one photo, mark all their thumbnails with the slidesinview event:
main.on('slidesinview', () => {
const list = main.slidesInView();
thumbs.slideNodes().forEach((node, index) => node.classList.toggle('in_view', list.includes(index)));
});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
1
2
3
4
5
6
7
8
9
10duration: 800: a slower motion
1
2
3
4
5
6
7
8
9
10<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>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.
1
2
3
4
5
6
7<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>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();
}
}
});.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:
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
}
});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.
<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:
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
}
});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.
1
2
3
4
5
6
7<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>.better::before {
content: "";
display: block;
height: 4px;
margin-bottom: 12px;
background: currentColor;
transform-origin: left;
scale: var(--better-progress, 0) 1;
}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.
1
2
3
4
5
6<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>.better .item {
overflow: hidden;
}
.better .item img {
scale: 1.3;
translate: calc(clamp(-1, var(--better-offset, 0), 1) * -10%) 0;
}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.
1
2
3
4
5
6
7<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>.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));
}A function in place of true gets the values that CSS cannot calculate. In this example:
progress function writes the position between the snaps, for example 2.4, and the progress in percent;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.
1
2
3
4
5
6
7const 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).
| Option | Type | Default | Description |
|---|---|---|---|
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) |
loop | boolean | false | The 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) |
dragFree | boolean, 'snap' | false | true: glide after a drag and stop at any position. 'snap': glide and stop at the nearest snap. (example) |
dragFriction | number | 1 | The 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) |
slidesPerSnap | number, 'auto' | 1 | The number of slides in one snap. 'auto': the slides that fit in the viewport. (example) |
skipSnaps | boolean, number | true | The 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) |
snapOverdrag | number | 0.5 | The 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) |
dragThreshold | number | 10 | The distance in px that the pointer moves before a drag starts. |
duration | number | 500 | The duration of a motion by one snap, in ms. A longer motion takes more time, to a maximum of 2 times this value. (example) |
startSnap | number | 0 | The index of the snap at the start. (example) |
lazy | boolean, number | false | true: start when the carousel comes within one screen of the view. A number: the distance in px. (example) |
drag | boolean | true | Drag 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. |
wheel | boolean, 'both' | true | The 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) |
keys | boolean | true | The 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. |
resize | boolean | true | Measure again when a size changes. (example) |
slideChanges | boolean | true | Measure again when the page adds or removes a slide. (example) |
focus | boolean | true | Go to a slide when it gets the keyboard focus. (example) |
inViewThreshold | number | 0 | The part of a slide, from 0 to 1, that must show for slidesInView(). (example) |
active | boolean | true | false: do not start the carousel. Use it in breakpoints. (example) |
breakpoints | object | {} | The options for media queries: { '(min-width: 768px)': { loop: true } }. (example) |
container | string | null | The selector of the container, if the element is the root. |
slides | string | null | The selector of the slides. With null, all children of the container are slides. |
wrapper | boolean | true | Add the root and the viewport if the page does not have them. (example) |
arrows | boolean, Element, string | true | Add the arrows to the root. false: no arrows. An element or a selector: add the arrows to that element. (example) |
dots | boolean, Element, string | true | Add 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) |
labels | object | English | The 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) |
classes | string, object | null | A class prefix such as 'embla', or an object with the names to change. The Classes table gives all names. (example) |
state | string | '' | The prefix of the state classes, such as 'is_'. (example) |
sync | carousel, Element, string | null | Another 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) |
autoplay | boolean, number, object | false | Go to the next slide after a delay. true, a delay in ms, or an object. (example) |
autoScroll | boolean, number, object | false | Move the slides at a constant speed. true, a speed in px/s, or an object. (example) |
autoHeight | boolean | false | The 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) |
progress | boolean, function | false | Follow 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. |
offset | boolean, function | false | Follow 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. |
BetterCarousel(element, options) returns the carousel. The table gives the methods of the carousel, and of the BetterCarousel function.
| Method | Returns | Description |
|---|---|---|
BetterCarousel(element, options) | carousel | Start 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() | boolean | true if a next or a previous snap exists. In a loop, true if not all slides fit. |
selectedSnap(), previousSnap() | number | The index of the selected snap, or of the snap before it. |
selectedSlide() | number | The index of the selected slide. With sync, the slide that is selected in the other carousel. |
snapOfSlide(index) | number | The index of the snap that shows a slide. |
snapProgress() | number[] | The progress of each snap, from 0 to 1. |
progress() | number | The 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() | HTMLElement | The root, the viewport and the container. |
isFit() | boolean | true if all slides fit in the viewport. |
options() | object | The 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) | carousel | Add or remove an event handler. The handler gets (carousel, name). |
autoplay | object | Only with the autoplay option: play(), stop(), reset() and isPlaying(). |
autoScroll | object | Only with the autoScroll option: play(), stop() and isPlaying(). |
BetterCarousel.get(element) | carousel, undefined | The 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.defaults | object | The options for all carousels. Set it before you start the carousels. |
const carousel = BetterCarousel(element, { loop: true });
carousel.on('select', (carousel) => {
console.log('Slide', carousel.selectedSlide());
});
document.querySelector('.next').addEventListener('click', () => carousel.goToNext());Add a handler with on(name, handler), and remove it with off(name, handler). The handler gets (carousel, name).
| Event | When |
|---|---|
init | The carousel measured the layout for the first time. |
reinit | A reinit() call or a breakpoint started the carousel again. |
resize | The layout changed. |
select | The selected snap changed. |
scroll | The position changed during a motion or a drag. |
settle | A motion stopped. |
dragstart, dragend | A drag started or stopped. |
slidesinview | The slides in view changed. |
slideschanged | The page added, removed or replaced a slide. |
slidefocus | A slide got the keyboard focus. |
autoplay:play, autoplay:stop | The autoplay started or stopped. |
autoscroll:play, autoscroll:stop | The auto scroll started or stopped. |
destroy | The 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.
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.
| Class | Element |
|---|---|
better | The root |
better_viewport | The viewport |
better_container | The container |
better_horizontal, better_vertical | The axis, on the root |
better_fit | On the root, if all slides fit |
better_auto_height | On the root, with autoHeight |
better_button, better_prev, better_next, better_play | The buttons |
better_dots, better_dot | The window of the dots, and the dots |
better_dots_track, better_dots_marker | With 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_all | On the window of the dots, with dotsStyle: 'glide' and 'all' |
selected | The selected slide |
clone | A clone of a slide |
dragging | On the root, during a drag |
playing | On the root, while the autoplay or the auto scroll plays |
current, prev, next, first, last | The selected dot and the four dots around it. With dotsStyle: 'all', only current. |
// .embla, .embla_viewport, .embla_button, .is_selected
BetterCarousel(element, { classes: 'embla', state: 'is_' });
// Change one name
BetterCarousel(element, { classes: { selected: 'snapped' } });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.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15<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.
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.
| Embla | Embla name | Better Carousel |
|---|---|---|
| 9 | Handler (api, event) | Handler (carousel, name). The events have no detail. |
| 9 | Autoplay delay as a function that gives one delay for each snap | Autoplay delay as an array with one delay for each snap |
| 8 | Option startIndex | startSnap |
| 8 | Options watchDrag, watchResize, watchSlides, watchFocus | drag, resize, slideChanges, focus |
| 9 | Option draggable | drag |
| 8, 9 | Options slidesToScroll, direction | slidesPerSnap, dir |
| 8, 9 | Autoplay and AutoScroll stopOnMouseEnter, stopOnFocusIn | pauseOnHover, pauseOnFocus |
| 8, 9 | AutoScroll direction: 'forward', 'backward' | direction: 'next', 'prev' |
| 8 | Autoplay jump | instant |
| 8 | scrollTo(index, jump) | goToSnap(index, instant) |
| 9 | goTo(index, instant) | goToSnap(index, instant) |
| 8 | scrollNext(), scrollPrev() | goToNext(), goToPrev() |
| 8 | canScrollNext(), canScrollPrev() | canGoToNext(), canGoToPrev() |
| 8 | selectedScrollSnap(), previousScrollSnap() | selectedSnap(), previousSnap() |
| 8 | scrollSnapList() | snapProgress() |
| 9 | snapList() | snapProgress() |
| 8, 9 | scrollProgress(), reInit() | progress(), reinit() |
| 8 | Events reInit, slidesInView, slidesChanged, slideFocus | reinit, slidesinview, slideschanged, slidefocus |
| 8 | Events pointerDown, pointerUp | dragstart, dragend |
| 9 | Events pointerdown, pointerup | dragstart, dragend |
| 8, 9 | Plugins Autoplay, AutoScroll, AutoHeight | The options autoplay, autoScroll, autoHeight |
| 8, 9 | plugins().autoplay, plugins().autoScroll | carousel.autoplay, carousel.autoScroll |
| 8, 9 | Plugin ClassNames | The options classes and state |
| 8, 9 | Plugin WheelGestures (a separate package) | The option wheel |
The carousel follows the carousel pattern of the WAI-ARIA Authoring Practices and WCAG 2.1 AA.
article or a list item keeps its own role.aria-live), but not during the autoplay.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.To translate the labels, set labels. In the texts, %d is the slide number, and %n is the number of slides:
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',
},
};The library is made for slow phones. A motion runs on the compositor, and a carousel at rest uses no CPU.
translate. No script runs for each frame.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.translate. A click on a dot causes no layout work.progress and offset options run a script on each frame of a motion. For this reason, they are off by default.| File | Minified | Gzip | Brotli |
|---|---|---|---|
better-carousel.min.js | 32.3 KB | 13.3 KB | 12.1 KB |
better-carousel.css | 5.1 KB | 1.5 KB | 1.2 KB |
| Total | 37.4 KB | 14.8 KB | 13.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.
| Measure | Better | Swiper | Embla | Glide |
|---|---|---|---|---|
| 6 slide changes, main-thread ms | 118 | 128 | 866 | 197 |
| 5 drags, main-thread ms | 519 | 619 | 1477 | 816 |
| Autoplay, CPU % | 0.6 | 16.7 | 16.9 | 1.6 |
| Dropped or late frames on a busy page, % | 1.9 | 3.0 | 15.5 | 0.7 |
| Total Blocking Time, 10 carousels, ms | 41 | 65 | 42 | 54 |
| All features, JS and CSS, KB gzip | 15.0 | 32.9 | 13.7 | not available |
The README gives the method, the desktop values and the feature list.
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.
BetterCarousel.initAll('.items.carousel', { lazy: true });
// Start within 300 px of the view
BetterCarousel.initAll('.items.carousel', { lazy: 300 });BetterCarousel.get() gives the carousel, but rootNode() is undefined and slideNodes() is empty.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.
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.
1
2
3
4
5
6
7
8<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>