Aero Slider v1.2.3

Menu

7.8 KB core · 10.7 KB full · 0 dependencies

CSS-first slider for the modern web

.zip

bun add aero-slider

AI Guide aeroslider.md

CSS-first

Responsive in CSS with media queries instead of JavaScript breakpoint objects.

@media (min-width: 768px) {
  .aero-slider {
    --aero-slides-per-view: 2;
  }
}

Native scroll

The browser does the scrolling. Touch, trackpad and momentum feel native because they are, with CSS scroll snapping holding each slide.

Zero layout shift

Slides get their size from CSS before any JavaScript runs, so nothing jumps or has to be covered up.

7.8 KB core, 10.7 KB full, 0 dependencies

The core is 6.9 KB of JavaScript and 0.9 KB of CSS, gzipped. Looping, autoplay, scrolling dots and thumbnail sync are extensions: ship only the ones you use, or the full file with all of them.

Playground

Slide One01
Slide Two02
Slide Three03
Slide Four04
Slide Five05
Code HTML · CSS · JS
<div id="slider" class="aero-slider" role="region" aria-roledescription="carousel" aria-label="Featured">
  <div class="aero-slider__viewport">
    <button type="button" class="aero-slider__nav--prev" aria-label="Previous slide">‹</button>
    <button type="button" class="aero-slider__nav--next" aria-label="Next slide">›</button>
    <div class="aero-slider__track">
      <div role="group" aria-roledescription="slide" aria-label="1 of 5">Slide 1</div>
      <div role="group" aria-roledescription="slide" aria-label="2 of 5">Slide 2</div>
      <!-- … 5 slides in total -->
    </div>
  </div>
  <div class="aero-slider__pagination" role="group" aria-label="Slides">
    <button type="button" class="aero-slider__dot" aria-label="Go to slide {index}"></button>
  </div>
</div>

Get started

  1. 01 Markup

    A container, a viewport and a track. Each child of the track is a slide.

    Arrows and dots are optional.

    You write the roles and labels. The slider keeps state such as aria-current up to date.

    HTML
    <div class="aero-slider" role="region" aria-roledescription="carousel" aria-label="Featured">
      <div class="aero-slider__viewport">
        <!-- Optional: arrows, placed before the track -->
        <button type="button" class="aero-slider__nav--prev" aria-label="Previous slide">‹</button>
        <button type="button" class="aero-slider__nav--next" aria-label="Next slide">›</button>
    
        <div class="aero-slider__track">
          <div role="group" aria-roledescription="slide" aria-label="1 of 3">Slide 1</div>
          <div role="group" aria-roledescription="slide" aria-label="2 of 3">Slide 2</div>
          <div role="group" aria-roledescription="slide" aria-label="3 of 3">Slide 3</div>
        </div>
      </div>
    
      <!-- Optional: pagination, with one dot as a template -->
      <div class="aero-slider__pagination" role="group" aria-label="Slides">
        <button type="button" class="aero-slider__dot" aria-label="Go to slide {index}"></button>
      </div>
    </div>
  2. 02 Load it

    Load it one of three ways:

    • Install the package from npm.
    • Link the files from a CDN.
    • Download the files from the latest release.

    The CDN and the release include a full file with every extension, which sets up a global AeroSlider. They also include the core and each extension as separate files, so you can load only what you need.

    With the package, call use() for each extension you use.

    import { createSlider, use, loop } from "aero-slider";
    import "aero-slider/slider.css";
    
    use({ loop }); // only the extensions you use
  3. 03 Create it

    Pass the container and any options. It returns the slider instance, which is also stored on the element as element.aeroSlider.

    const slider = createSlider(document.querySelector(".aero-slider"), { loop: true });

Three layers

A container holds a viewport and a pagination row. The viewport holds the previous and next buttons and the track, and the track holds the slides. The pagination row holds one dot template and its clones. .aero-slider __viewport __track __nav--prev __pagination __nav--next slides __dot
HTML

HTML decides what exists

Arrows and dots are not JavaScript options. If the elements are inside the container, the slider finds them and wires them up. The dot is one template that the slider clones for each position it can scroll to.

CSS

CSS variables decide how it looks

--aero-slides-per-view, --aero-slide-gap and --aero-slide-aspect, set on the container and changed in media queries.

JS

JS config decides how it behaves

snap, vertical and the other options, plus extension options such as loop and autoplay.

The library ships layout only. Arrows and dots have no styles, so you style them yourself.

Examples

01 Layout

Gallery that follows the variant

Color
On switch
Code HTML · CSS · JS
<div id="swatches" role="group" aria-label="Color">
  <button type="button" data-variant="graphite">Graphite</button>
  <button type="button" data-variant="ceramic">Ceramic</button>
  <button type="button" data-variant="blue">Blue</button>
</div>

<div id="variant-gallery" class="aero-slider" role="region" aria-roledescription="carousel" aria-label="Product images">
  <div class="aero-slider__viewport">
    <div class="aero-slider__track">
      <!-- data-variant: shown for that color only -->
      <div data-variant="graphite">Graphite, front</div>
      <div data-variant="graphite">Graphite, side</div>
      <div data-variant="ceramic">Ceramic, front</div>
      <div data-variant="ceramic">Ceramic, side</div>
      <div data-variant="blue">Blue, front</div>
      <div data-variant="blue">Blue, side</div>
      <!-- No data-variant: shown for every color -->
      <div>Fit guide</div>
    </div>
  </div>
</div>

<!-- One button per slide, in the same order, with the same data-variant -->
<div id="variant-thumbs" class="aero-slider" role="group" aria-label="Product image thumbnails">
  <div class="aero-slider__viewport">
    <div class="aero-slider__track">
      <button type="button" data-variant="graphite" aria-label="Show graphite, front">…</button>
      <!-- … -->
      <button type="button" aria-label="Show fit guide">…</button>
    </div>
  </div>
</div>
Good to know
  • refresh() re-reads the slides from the track, so the slider becomes whatever elements are in it. Change the track first, then call it.
  • Take slides out of the track to hide them. One hidden with CSS still counts as a slide, with its own stop and dot.
  • refresh() keeps the current index. Call goTo(0, { instant: true }) after it to start the new set from its first image, with no flash.
  • Find slides by data-aero-slider-index, not by their place in the track, which also holds loop clones.
  • Reusing the same elements keeps the images they have already loaded.
  • No slideChange fires when the set changes under the same index. Update a counter or caption yourself after the swap.
  • Update slide labels such as "2 of 5" when the count changes.

02 Layout

Edge-to-edge carousel

Alignment
Aligned01The active card lines up with the content column.
Bleed02The track reaches both edges of the window.
Column03Slides size against the column, not the window.
Wrapper04Your page owns the full-bleed wrapper around it.
Edges05The first and last cards land on the column too.
Code HTML · CSS · JS
<div class="breakout-clip">
  <div id="edge-to-edge" class="aero-slider aero-slider--breakout" role="region" aria-roledescription="carousel" aria-label="Featured">
    <div class="aero-slider__viewport">
      <button type="button" class="aero-slider__nav--prev" aria-label="Previous slide">‹</button>
      <button type="button" class="aero-slider__nav--next" aria-label="Next slide">›</button>
      <div class="aero-slider__track">
        <div role="group" aria-roledescription="slide" aria-label="1 of 5">Slide 1</div>
        <div role="group" aria-roledescription="slide" aria-label="2 of 5">Slide 2</div>
        <div role="group" aria-roledescription="slide" aria-label="3 of 5">Slide 3</div>
        <!-- … 5 slides in total -->
      </div>
    </div>
    <div class="aero-slider__pagination" role="group" aria-label="Slides">
      <button type="button" class="aero-slider__dot" aria-label="Go to slide {index}"></button>
    </div>
  </div>
</div>
Good to know
  • aero-slider--breakout lets the viewport overflow and pads the track so the first and last slides line up with the column.
  • --aero-layout-width is the width slides are sized against. Set it to your content column.
  • The wrapper must span the window. Hide the page's horizontal overflow, because 100vw includes the scrollbar.

03 Layout

Slider on phones, grid on desktop

CollectionWatches
CollectionOuterwear
CollectionEyewear
CollectionBags
CollectionGloves
CollectionInstruments
Code HTML · CSS · JS
<div id="collections" class="aero-slider" role="region" aria-roledescription="carousel" aria-label="Collections">
  <div class="aero-slider__viewport">
    <div class="aero-slider__track">
      <div role="group" aria-roledescription="slide" aria-label="1 of 6">Slide 1</div>
      <div role="group" aria-roledescription="slide" aria-label="2 of 6">Slide 2</div>
      <div role="group" aria-roledescription="slide" aria-label="3 of 6">Slide 3</div>
      <!-- … 6 slides in total -->
    </div>
  </div>
</div>
Good to know
  • destroy() removes the slider's listeners, clones and state classes and leaves your markup, so the same elements can become a grid and be started again later.
  • The track keeps its flex row until your CSS replaces it. That is the one rule in the media query.
  • Keep the breakpoint in the script and the one in the stylesheet the same.
  • Resize the window across 768px to watch it switch.

04 Motion

Hero banner with autoplay

New seasonAutumnField jackets and wool layers, in now.
Back in stockWatchesThe Field Watch returns in three colors.
CollectionTravelDuffels and cases built for the overhead bin.
Under $50GiftsSmall things that get used every day.
Code HTML · CSS · JS
<div id="hero-banner" class="aero-slider" role="region" aria-roledescription="carousel" aria-label="Featured" data-aero-defer-visibility>
  <div class="aero-slider__viewport">
    <button type="button" class="aero-slider__nav--prev" aria-label="Previous slide">‹</button>
    <button type="button" class="aero-slider__nav--next" aria-label="Next slide">›</button>
    <div class="aero-slider__track">
      <div role="group" aria-roledescription="slide" aria-label="1 of 4">Slide 1</div>
      <div role="group" aria-roledescription="slide" aria-label="2 of 4">Slide 2</div>
      <div role="group" aria-roledescription="slide" aria-label="3 of 4">Slide 3</div>
      <!-- … 4 slides in total -->
    </div>
  </div>
  <div class="aero-slider__pagination" role="group" aria-label="Slides">
    <button type="button" class="aero-slider__dot" aria-label="Go to slide {index}"></button>
  </div>
</div>
Good to know
  • It pauses on hover, focus, press and drag, and while the tab is hidden. It is off under prefers-reduced-motion. A manual change restarts the countdown.
  • Autoplay always loops, so it needs the loop extension too.
  • Autoplay that runs for more than five seconds needs a pause control. Wire your own button to pause() and resume().
  • A loop puts clones of the last slides in front of the first. Where neighboring slides show, as here, data-aero-defer-visibility reserves their space in CSS so slide 1 doesn't jump when JavaScript starts.
  • The reserved space is worked out from --aero-slides-per-view and --aero-slide-gap for center alignment. With another alignment, repeat it in the HTML as data-aero-alignment="start" or "end".

05 Motion

Logo ticker

Aurelo
Novaline
Quillbridge
Stratum Six
Ferrovane
Lumenkin
Orrery
Halvard
Code CSS · JS
#ticker {
  --aero-slides-per-view: 4;
  --aero-slide-gap: 12px;
  --aero-slide-aspect: 5 / 2;
}
Good to know
  • autoplay: "continuous" drifts the track at autoplaySpeed pixels per second. Like all autoplay it loops, so it needs the loop extension, and it implies snap: "none".
  • The drift uses Web Animations, not per-frame JavaScript, so a busy main thread doesn't stall it.
  • Hovering doesn't pause it. Pressing, keyboard focus and pause() do.
  • Wheel and trackpad scrolling add to the drift.
  • Under prefers-reduced-motion the track stays still.
  • draggable: false keeps a mouse press from grabbing the strip. Leave it on if people should scrub through it.

06 Motion

Announcement bar

Free shipping on orders over $50
Free returns within 30 days
New: the Autumn field collection
Code HTML · CSS · JS
<div id="announcement" class="aero-slider aero-slider--vertical" role="region" aria-roledescription="carousel" aria-label="Announcements">
  <div class="aero-slider__viewport">
    <div class="aero-slider__track">
      <div role="group" aria-roledescription="slide" aria-label="1 of 3">Free shipping on orders over $50</div>
      <div role="group" aria-roledescription="slide" aria-label="2 of 3">Free returns within 30 days</div>
      <div role="group" aria-roledescription="slide" aria-label="3 of 3">New: the Autumn field collection</div>
    </div>
  </div>
</div>
Good to know
  • vertical: true scrolls top to bottom, whatever the text direction of the page. The up and down arrow keys, the drag axis and a swipe all follow.
  • A vertical slider gets its height from its viewport. Give the viewport a height, as here, or let it follow --aero-slide-aspect.
  • The slider adds aero-slider--vertical itself. Putting the class in the markup as well lays the bar out before JavaScript runs.

08 Controls

Product row

Field Watch $148
Flight Jacket $320
Aviator Glasses $96
Kneeboard $42
Headset Case $58
Duffel 40L $184
Leather Gloves $74
Chart Pen $18
Code HTML · CSS · JS
<div id="product-row" class="aero-slider" role="region" aria-roledescription="carousel" aria-label="Best sellers">
  <div class="aero-slider__viewport">
    <button type="button" class="aero-slider__nav--prev" aria-label="Previous slide">‹</button>
    <button type="button" class="aero-slider__nav--next" aria-label="Next slide">›</button>
    <div class="aero-slider__track">
      <div role="group" aria-roledescription="slide" aria-label="1 of 8">
        <article class="card">
          <img src="field-watch.jpg" alt="" />
          <a href="/products/field-watch">Field Watch</a>
          <button type="button">Add to cart</button>
        </article>
      </div>
      <div role="group" aria-roledescription="slide" aria-label="2 of 8">
        <article class="card">
          <img src="flight-jacket.jpg" alt="" />
          <a href="/products/flight-jacket">Flight Jacket</a>
          <button type="button">Add to cart</button>
        </article>
      </div>
      <div role="group" aria-roledescription="slide" aria-label="3 of 8">
        <article class="card">
          <img src="aviator-glasses.jpg" alt="" />
          <a href="/products/aviator-glasses">Aviator Glasses</a>
          <button type="button">Add to cart</button>
        </article>
      </div>
      <!-- … 8 slides in total -->
    </div>
  </div>
</div>
Good to know
  • --aero-slides-per-view takes fractions. The part after the point is how much of the next card shows.
  • The slider re-reads --aero-slides-per-view whenever the track or a slide changes size along the track, so a media query takes effect with no JavaScript breakpoint config.
  • --aero-slide-aspect: auto lets a card take the height of its content. Leave it out to give every slide one shape.
  • The slider stretches each direct child of a slide to fill it, so wrap the card's content in one element, as here.
  • noDrag keeps a mouse drag from starting on the link and button, so they click as usual. Without it, a drag that starts on them swallows the click. Touch is not affected.
  • perMove sets how far the arrows, the arrow keys and autoplay go. Dragging still lands on any card.

09 Controls

Many slides, few dots

01
02
03
04
05
06
07
08
09
10
11
12
Code HTML · CSS · JS
<div id="max-dots" class="aero-slider" role="region" aria-roledescription="carousel" aria-label="Many slides">
  <div class="aero-slider__viewport">
    <button type="button" class="aero-slider__nav--prev" aria-label="Previous slide">‹</button>
    <button type="button" class="aero-slider__nav--next" aria-label="Next slide">›</button>
    <div class="aero-slider__track">
      <div role="group" aria-roledescription="slide" aria-label="1 of 12">Slide 1</div>
      <div role="group" aria-roledescription="slide" aria-label="2 of 12">Slide 2</div>
      <div role="group" aria-roledescription="slide" aria-label="3 of 12">Slide 3</div>
      <!-- … 12 slides in total -->
    </div>
  </div>
  <div class="aero-slider__pagination" role="group" aria-label="Slides">
    <button type="button" class="aero-slider__dot" aria-label="Go to slide {index}"></button>
  </div>
</div>
Good to know
  • With more positions than maxDots, the dots sit in a window that slides to keep the active one in view.
  • Dots at the window's edges get aero-slider__dot--edge and aero-slider__dot--near-edge, which the library's CSS shrinks.
  • 0, the default, shows every dot.

10 Controls

Counter and progress bar

View01
View02
View03
View04
View05
Code HTML · CSS · JS
<div id="counted" class="aero-slider" role="region" aria-roledescription="carousel" aria-label="Product images">
  <div class="aero-slider__viewport">
    <button type="button" class="aero-slider__nav--prev" aria-label="Previous slide">‹</button>
    <button type="button" class="aero-slider__nav--next" aria-label="Next slide">›</button>
    <div class="aero-slider__track">
      <div role="group" aria-roledescription="slide" aria-label="1 of 5">Slide 1</div>
      <div role="group" aria-roledescription="slide" aria-label="2 of 5">Slide 2</div>
      <div role="group" aria-roledescription="slide" aria-label="3 of 5">Slide 3</div>
      <!-- … 5 slides in total -->
    </div>
  </div>
</div>

<p id="gallery-count">1 / 5</p>
<div class="progress"><div id="gallery-bar"></div></div>
Good to know
  • aero:slideChange fires on the container as soon as the new slide is known, before the scroll lands, so the counter keeps up with a drag.
  • Read currentIndex and slideCount from the instance, or the index from event.detail.index.
  • The counter and bar are your own elements, anywhere on the page. Leave the pagination element out of the slider and it makes no dots.
  • Call the function again after you change the slides and refresh().

11 Controls

Arrows, dots and their states

01
02
03
04
05
Code HTML · CSS · JS
<div id="styled" class="aero-slider" role="region" aria-roledescription="carousel" aria-label="Styled controls">
  <div class="aero-slider__viewport">
    <button type="button" class="aero-slider__nav--prev" aria-label="Previous slide">‹</button>
    <button type="button" class="aero-slider__nav--next" aria-label="Next slide">›</button>
    <div class="aero-slider__track">
      <div role="group" aria-roledescription="slide" aria-label="1 of 5">Slide 1</div>
      <div role="group" aria-roledescription="slide" aria-label="2 of 5">Slide 2</div>
      <div role="group" aria-roledescription="slide" aria-label="3 of 5">Slide 3</div>
      <!-- … 5 slides in total -->
    </div>
  </div>
  <div class="aero-slider__pagination" role="group" aria-label="Slides">
    <button type="button" class="aero-slider__dot" aria-label="Go to slide {index}"></button>
  </div>
</div>
Good to know
  • Put the arrow buttons before the track, so keyboard users reach them before the slide content.
  • The dot is one template. The slider clones it for each position it can scroll to.
  • Give each button an aria-label. Make the dot a <button type="button"> too: a <span> cannot be reached by keyboard. {index} in its aria-label becomes the slide number of each dot.
  • The viewport is position: relative, so arrows inside it can be placed with position: absolute.
  • The slider sets disabled on an arrow that cannot go further, so :disabled styles the end state. With loop no arrow is ever disabled.
  • The current dot gets aero-slider__dot--active and aria-current="true".
  • Small dots are hard to tap. Make the button at least 24px wide and draw the dot inside it with ::before, as here.
  • Every class the slider sets is listed under States in the API.

API Reference

Function

createSlider(element, config?)

Turns a container into a slider and returns its instance, also stored as element.aeroSlider. config takes any of the options below.

Arrows and dots are not options. Put them in the markup and the slider wires them up; see arrows and dots.

JavaScript
import { createSlider, use, loop } from "aero-slider";

use({ loop }); // the loop option needs the loop extension
const el = document.querySelector(".aero-slider");
const slider = createSlider(el, { loop: true });

el.aeroSlider === slider; // true
Throws
aero-slider: missing .aero-slider__track No track element inside the container.
aero-slider: no slides found The track has no children.

Config

Options

The second argument to createSlider. Every option is optional. Change them later with slider.update().

Layout

  • alignment
    Type: "start" | "center" | "end" default "center"
    Where the active slide sits in the viewport. start is the left edge, the right edge in a right-to-left slider and the top in a vertical one. Without loop, the scroll stops at the ends, but currentIndex still names the active slide.
    See example
  • vertical
    Type: boolean default false
    Scrolls top to bottom. Without it, the slider is horizontal and follows dir="rtl". Call refresh() after changing dir.
    See example
  • perMove
    Type: number default 1
    How many slides next(), prev(), the arrows, the arrow keys and autoplay move at once.
    See example

Interaction

  • draggable
    Type: boolean default true
    Lets a mouse or pen drag the track. Touch always swipes natively.
  • noDrag
    Type: string default form fields
    Elements inside slides where a mouse drag should not start. The default, "input, textarea, select, [contenteditable]", keeps form fields working. Your value replaces it. Links and buttons are left out so a slide that is a link can still be dragged.
    See example

Motion

  • snap
    Type: "native" | "settle" | "none" default "native"
    How the track comes to rest. "native" uses CSS scroll snapping. "settle" scrolls freely, then eases onto the nearest slide. "none" stops wherever the scroll ends.
  • scrollDuration
    Type: number default 0
    How long, in ms, next(), prev() and goTo() take to scroll, eased by scrollEasing. 0 uses native smooth scrolling. Instant under prefers-reduced-motion.
  • scrollEasing
    Type: (t: number) => number default ease-out cubic
    Maps progress from 0 to 1 onto eased progress for scrollDuration scrolls. (t) => t is linear.

CSS

Variables and attributes

Size and spacing live in CSS, set on the container. The slider re-measures on its own when the container or a slide changes size, including from media queries and loaded images. After you change a variable from script, call refresh().

Custom properties

  • --aero-slides-per-view
    default 1
    How many slides fit the viewport, 1 or more. Fractions such as 1.5 show a peek of the next slide.
    See example
  • --aero-slide-gap
    default 0px
    Space between slides.
  • --aero-slide-aspect
    default 5 / 3
    Aspect ratio of each slide, so the slider has its height before JavaScript runs.
  • --aero-layout-width
    default 100%
    The content column for an aero-slider--breakout slider. Slides size to this column while the track runs to the edges of the screen.
    See example

HTML attributes

  • data-aero-alignment
    Type: "start" | "center" | "end"
    The slider sets this from alignment. Write it in your HTML too when you use a non-center alignment, so snapping and the reserved space match before JavaScript runs.
    See example
  • data-aero-status
    Type: string default "{index} of {count}"
    What screen readers hear when the slide changes, for example Bild {index} von {count}.

The slider also adds state classes such as aero-slider--dragging to the container. They are listed under States.

CSS

States

Classes the slider sets on the container and its controls. See arrows, dots and their states for an example.

Container states

  • aero-slider--ready
    The slider has initialized.
  • aero-slider--draggable
    draggable is on. The track shows the grab cursor only then.
  • aero-slider--dragging
    A mouse or pen drag is in progress (grabbing cursor).
  • aero-slider--free
    snap is "settle" or "none". Turns CSS scroll snapping off.
  • aero-slider--vertical
    vertical is on.

Control states

  • aero-slider__dot--active
    The dot for the current position.
  • :disabled
    Set on aero-slider__nav--prev or --next when it cannot go further. Never with loop.

Instance

Methods

createSlider returns an instance with methods to move, pause, change and tear down the slider.

Navigate

  • .next()
    Moves forward by perMove stops. Stops at the last slide unless loop is on.
  • .prev()
    Moves back by perMove stops. Stops at the first slide unless loop is on.
  • .goTo(index, options?)
    Scrolls to slide index. Out-of-range indexes wrap on a loop and clamp otherwise. { instant: true } skips the animation. Use it instead of scrolling the track yourself.

Change

  • .update(config?)
    Merges new options into the config and rebuilds, keeping the current slide.
  • .refresh()
    Re-reads the slides from the track and rebuilds, resting on the same index. Call it after you add, remove or replace slides, and after you change a CSS variable from script. A slide hidden with CSS still counts, so take it out of the track.

Read state

  • .element
    Type: HTMLElement
    The container the slider runs on.
  • .currentIndex
    Type: number
    Index of the active slide. Loop clones are not counted.
  • .slideCount
    Type: number
    Number of slides, not counting loop clones.

Lifecycle

  • .destroy()
    Fires aero:destroy, then removes its listeners, clones and classes and deletes element.aeroSlider. Your markup stays, so createSlider can start it again.

The instance stays on element.aeroSlider until destroy().

DOM events

Events

The slider fires bubbling CustomEvents on its container, named with the aero: prefix, with data on event.detail. In the recipes, el is the container.

Listen
el.addEventListener("aero:slideChange", (event) => {
  console.log(event.detail.index);
});

Navigation

  • aero:slideChange
    event.detail: { index: number }
    The active slide changed, however it moved. Fires as soon as the new slide is known, before the scroll lands.

    Use it for A “2 / 5” counter, analytics, or keeping your own UI in step with the slider.

    Recipe JS
    Recipe
    const counter = document.querySelector(".slide-counter");
    const slider = createSlider(el, { loop: true });
    const show = (index) => {
      counter.textContent = `${index + 1} / ${slider.slideCount}`;
    };
    
    show(slider.currentIndex); // no slideChange for the starting slide
    el.addEventListener("aero:slideChange", (event) => show(event.detail.index));

Visibility

  • aero:visible
    event.detail: { index: number }
    A slide came into view, even partly. Loop clones report the index of the slide they copy. Once the slider starts, it fires for every slide already in view.

    Use it for Lazy-loading an image or starting a video when its slide comes into view.

    Recipe JS
    Recipe
    // Each slide holds <img data-src="photo.jpg" alt="">.
    el.addEventListener("aero:visible", (event) => {
      const track = el.querySelector(".aero-slider__track");
      // Real slides carry data-aero-slider-index; loop clones don't.
      const slide = track.querySelector(`[data-aero-slider-index="${event.detail.index}"]`);
      const src = slide.querySelector("img[data-src]")?.dataset.src;
      if (!src) return;
      // Clones are copies of the slide, so load every copy of the image.
      for (const img of track.querySelectorAll("img[data-src]")) {
        if (img.dataset.src !== src) continue;
        img.src = src;
        img.removeAttribute("data-src");
      }
    });
    createSlider(el, { loop: true });
  • aero:hidden
    event.detail: { index: number }
    A slide went fully out of view.

    Use it for Pausing a video, or any other work, when its slide leaves the view.

    Recipe JS
    Recipe
    // Some slides hold <video muted playsinline loop>.
    // A loop comes to rest on real slides, so the real copy is the one in view.
    const videoIn = (index) =>
      el.querySelector(`[data-aero-slider-index="${index}"] video`);
    
    el.addEventListener("aero:visible", (event) => videoIn(event.detail.index)?.play());
    el.addEventListener("aero:hidden", (event) => videoIn(event.detail.index)?.pause());

Drag

  • aero:dragStart
    event.detail: { index: number }
    A mouse or pen drag began. index is the slide it started from. Touch swipes fire no drag events; use aero:slideChange to follow every move.

    Use it for Reacting to the first drag, such as removing a “drag to explore” hint.

    Recipe JS
    Recipe
    const hint = el.querySelector(".drag-hint");
    el.addEventListener("aero:dragStart", () => hint.remove(), { once: true });
  • aero:dragEnd
    event.detail: { index: number; fromIndex: number }
    The drag was released and the slider chose where to settle. fromIndex is where it started, index where it is going. Mouse and pen only, like aero:dragStart.

    Use it for Logging drags. You don't need it to block clicks: the slider already swallows the click that ends a drag.

    Recipe JS
    Recipe
    el.addEventListener("aero:dragEnd", (event) => {
      const { fromIndex, index } = event.detail;
      if (index !== fromIndex) console.log(`dragged from ${fromIndex} to ${index}`);
    });

Layout

  • aero:resize
    event.detail: {}
    The slider or one of its slides changed size along the track. Fires before the slider re-measures and moves the slides back into place.

    Use it for Hiding anything pinned to where a slide was, before the slider moves it.

    Recipe JS
    Recipe
    // A tooltip pinned to a slide would point at the wrong spot once slides move.
    const tip = document.querySelector(".slide-tip");
    el.addEventListener("aero:resize", () => {
      tip.hidden = true;
    });
  • aero:resized
    event.detail: {}
    The slider has re-measured after a resize and put the active slide back in place.

    Use it for Recomputing anything that depends on slide size or position.

    Recipe JS
    Recipe
    // Hand the slide width to CSS, e.g. to size captions outside the track.
    const setSlideWidth = () => {
      const slide = el.querySelector("[data-aero-slider-index]");
      el.style.setProperty("--slide-width", `${slide.offsetWidth}px`);
    };
    
    el.addEventListener("aero:ready", setSlideWidth);
    el.addEventListener("aero:resized", setSlideWidth);
    createSlider(el);

Lifecycle

  • aero:ready
    event.detail: {}
    createSlider finished setting up. Fires before createSlider returns, so listen first, or check el.aeroSlider later. The container also gets aero-slider--ready.

    Use it for Setup that needs the instance when other code creates the slider, such as a framework component or a CMS block.

    Recipe JS
    Recipe
    // Works whether this runs before or after createSlider.
    function setUp(slider) {
      const counter = slider.element.querySelector(".slide-counter");
      if (counter) counter.textContent = `${slider.currentIndex + 1} / ${slider.slideCount}`;
    }
    
    if (el.aeroSlider) setUp(el.aeroSlider);
    else el.addEventListener("aero:ready", () => setUp(el.aeroSlider), { once: true });
  • aero:destroy
    event.detail: {}
    destroy() was called. It fires first, while the instance still works, and teardown follows.

    Use it for Removing your own listeners and timers that belong to this slider.

    Recipe JS
    Recipe
    const slider = createSlider(el);
    const listeners = new AbortController();
    
    // Your own listeners for this slider share one signal…
    document.addEventListener("keydown", (event) => event.key === "n" && slider.next(), {
      signal: listeners.signal,
    });
    // …so they all go when it does.
    el.addEventListener("aero:destroy", () => listeners.abort(), { once: true });
Note 01 Gotcha

One listener for every slider

Events bubble, so a listener on document hears every slider on the page. event.target is the container and event.target.aeroSlider its instance. If sliders nest, check event.target === el.

Note 02 TypeScript

Typing event data

addEventListener types these events as a plain Event. Cast to CustomEvent with the exported SliderEventData to type detail.

TypeScript
import type { SliderEventData } from "aero-slider";

type DragEnd = CustomEvent<SliderEventData<"dragEnd">>;

el.addEventListener("aero:dragEnd", (event) => {
  const { detail } = event as DragEnd;
  console.log(detail.fromIndex, detail.index);
});

Overview

Extensions

The core, 7.8 KB gzipped, has slides, arrows, dots, the keyboard, drag, snapping and every event. Looping, autoplay, scrolling dots and thumbnail sync are extensions. The full file, 10.7 KB, has all of them, ready to use.

An option whose extension isn't loaded does nothing, and the console says which extension it needs.

Autoplay requires the loop extension, because autoplay always loops.

Without a bundler, load the core file and then each extension file after it, or join them into one file in that order.

import { createSlider, use, loop, autoplay } from "aero-slider";
// The core's CSS and loop's. "aero-slider/slider.css" has every extension's.
import "aero-slider/core.css";
import "aero-slider/extensions/loop.css";

// Once, before creating sliders. Extensions you never import
// are left out of your bundle.
use({ loop, autoplay });

createSlider(el, { autoplay: true });
ExtensionAddsRequiresFiles in dist/extensionsGzipped
looploopcoreaero-slider.loop.min.js, aero-slider.loop.min.css1.2 KB
autoplayautoplay, interval and continuouscore + loopaero-slider.autoplay.min.js1.4 KB
scrollingDotsmaxDotscoreaero-slider.scrolling-dots.min.js, aero-slider.scrolling-dots.min.css1.0 KB
thumbnailssyncThumbnails()core, and loop for a looping stripaero-slider.thumbnails.min.js1.2 KB

Extension

Loop

dist/extensions/aero-slider.loop.min.jsdist/extensions/aero-slider.loop.min.css

Wraps from the last slide back to the first, using clones of the slides on both sides of the track. Clones are hidden from screen readers, the tab order and forms.

Cloned custom elements start up when inserted, so measure them in a ResizeObserver, not in the constructor.

Loop
01
02
03
04
05
06
Code CSS · JS
#ext-loop {
  --aero-slides-per-view: 2.5;
  --aero-slide-gap: 12px;
}
Requires
The core.

Options

  • loop
    Type: boolean default false
    Wraps from the last slide back to the first. Clones of the slides sit on both sides of the track, so scrolling never hits an end.

HTML attributes

  • data-aero-defer-visibility
    Reserves the space that loop clones will take before the slider starts, so a looping slider doesn't shift when JavaScript runs. Removed once it starts.
    See example

Extension

Autoplay

dist/extensions/aero-slider.autoplay.min.js

Moves the slider on its own: one move every interval, or a continuous drift like a ticker. It always loops, so it needs the loop extension too. Without it, autoplay stops at the last slide and the console says so.

Autoplay pauses while the slider is pressed, dragged or has keyboard focus, while the tab is hidden, and on pause(). Interval autoplay also pauses on hover. Neither kind runs under reduced motion.

Mode
Autoplay
01
02
03
04
05
06
07
08
Code CSS · JS
#ext-autoplay {
  --aero-slides-per-view: 3;
  --aero-slide-gap: 12px;
}
Requires
The core and the loop extension. Load loop first.

Options

  • autoplay
    Type: boolean | "continuous" default false
    Turns looping on. true moves once every autoplayInterval. "continuous" drifts like a ticker at autoplaySpeed, with snap: "none". Off under prefers-reduced-motion.
    See example
  • autoplayInterval
    Type: number default 5000
    Milliseconds between advances. Any slide change restarts the countdown, and it holds while the slider is hovered, focused or pressed.
    See example
  • autoplaySpeed
    Type: number default 40
    Speed of "continuous" autoplay in pixels per second. 0 or less keeps the track still.
    See example

Methods

  • .pause()
    Holds autoplay until resume(). Hover, focus and drag pauses still apply on top.
  • .resume()
    Releases pause() and starts a fresh autoplay countdown.

Events

  • aero:autoplayStart
    event.detail: {}
    Autoplay started or resumed. Never under prefers-reduced-motion. The first one fires inside createSlider, so listen before you create.

    Use it for A progress bar or a playing light that matches what autoplay is really doing.

    Recipe JS
    Recipe
    // <div class="autoplay-bar"> with transform-origin: left, inside the container.
    const interval = 4000;
    const bar = el.querySelector(".autoplay-bar");
    let fill = null;
    const restart = () => {
      fill?.cancel();
      fill = bar.animate([{ transform: "scaleX(0)" }, { transform: "scaleX(1)" }], {
        duration: interval,
      });
    };
    
    el.addEventListener("aero:autoplayStart", restart);
    // Every slide change restarts the countdown, so the bar starts over too.
    el.addEventListener("aero:slideChange", () => fill && restart());
    el.addEventListener("aero:autoplayStop", () => {
      fill?.cancel();
      fill = null;
    });
    createSlider(el, { autoplay: true, autoplayInterval: interval, loop: true });
  • aero:autoplayStop
    event.detail: {}
    Autoplay stopped running: on hover, keyboard focus, a press or drag, pause(), a hidden tab, update() turning it off, or destroy().

    Use it for Taking that progress bar or light down again. Pair it with aero:autoplayStart.

    Recipe JS
    Recipe
    // Style .is-playing as an indicator light that is on while autoplay runs.
    el.addEventListener("aero:autoplayStart", () => el.classList.add("is-playing"));
    el.addEventListener("aero:autoplayStop", () => el.classList.remove("is-playing"));
    createSlider(el, { autoplay: true, loop: true });

Extension

Scrolling dots

dist/extensions/aero-slider.scrolling-dots.min.jsdist/extensions/aero-slider.scrolling-dots.min.css

Shows at most maxDots pagination dots and scrolls the rest into view as the slider moves, the way iOS page indicators do. Plain dots are in the core; this extension adds the scrolling. See the example with many slides.

Dots
01
02
03
04
05
06
07
08
09
10
11
12
13
14
Code CSS · JS
#ext-scrolling-dots {
  --aero-slides-per-view: 2.5;
  --aero-slide-gap: 12px;
}
Requires
The core.

Options

  • maxDots
    Type: number default 0
    Shows at most this many pagination dots and slides the window along, iOS style. 0 shows them all.
    See example

Classes

  • aero-slider__dot--edge
    With maxDots: the outermost dot of the window when more dots lie beyond it. aero-slider__dot--near-edge marks the next one in, and aero-slider__dot--hidden the dots outside the window.

Extension

Thumbnails

dist/extensions/aero-slider.thumbnails.min.js

Links a thumbnail strip to a main slider: clicking a thumbnail shows that slide, and the strip follows the main slider. Both are made with createSlider. See the gallery example.

Strip loops
View01
View02
View03
View04
View05
View06
Code CSS · JS
#ext-main {
  --aero-slides-per-view: 1.3;
  --aero-slide-aspect: 16 / 9;
  --aero-slide-gap: 12px;
}

#ext-thumbs {
  --aero-slides-per-view: 5;
  --aero-slide-gap: 8px;
  --aero-slide-aspect: 16 / 9;
}
Requires
The core, and the loop extension for a looping strip, which is the default.

syncThumbnails(primary, thumbnails, options?)

Parameters

  • primary
    Type: SliderInstance
    The main slider.
  • thumbnails
    Type: SliderInstance
    The thumbnail strip. It needs the same number of slides as primary.
  • options.loop
    Type: boolean default true
    Whether the strip loops. Looping needs the loop extension.

Returns

  • teardown
    Type: () => void
    Removes the sync. Call it before destroying either slider.

What it does

  • Sets the strip's loop option. The strip can still be dragged.
  • Clicking a thumbnail shows that slide in primary.
  • Marks the active thumbnail with aero-slider__thumb--active and aria-current="true", and scrolls the strip to keep it in view.
  • Gives thumbnails that aren't already buttons or links role="button" and tabindex="0", so the keyboard can reach them. One with no label gets aria-label="Go to slide N".
  • Set alignment: "center" on the strip to keep the active thumbnail centered.
  • Teardown removes the sync's listeners, classes and attributes. It doesn't destroy either slider.

Classes

  • aero-slider__thumb--active
    Set by syncThumbnails on the thumbnail of the current slide.

Browser support

Chrome 88+, Firefox 89+ and Safari 16+.

CSS features by browser
CSS FeatureChromeSafariFirefoxUsed For
CSS Variables49+9.1+31+Configuring layout and gap size.
Scroll Snapping69+11+68+Locking slides into place after scrolling.
aspect-ratio88+15+89+Sizing slides from --aero-slide-aspect.
contain: paint52+15.4+69+Keeping slide painting inside the viewport.
overscroll-behavior-x63+16+59+Preventing rubber-banding when hitting the edge.