Jekyll One

Fulltext Search

Swiper is the free and most modern mobile touch slider with hardware accelerated transitions and amazing native behavior. It is intended to be used in mobile websites, mobile web apps, and mobile native/hybrid apps.

In the J1 Template, Swiper is the carousel engine behind every slider on your page. It is used together with PhotoSwipe to provide an optional lightbox, so visitors can not only swipe through your slides but also open each slide in a large overlay view. You can use Swiper on its own, of course, if you do not need the lightbox feature.

The Swiper API documentation pages are based on Swiper version v11.2.x for the current J1 template version 2026.x. The idea of providing this documentation is not to simply copy the original Swiper pages as duplicates. For better readability and usability, all pages are restructured and enhanced by code examples or improved description texts.

Overview

Swiper provides a complete carousel engine that can be operated via touch (mobile devices) and mouse/keyboard (desktop).

The Swiper API is the set of options, methods, properties and events you use from JavaScript to configure and control a slider. In J1 Template you usually do not call this API directly. Instead, you write a few YAML settings and the J1 swiper adapter (~/assets/theme/j1/adapter/js/swiper.js) builds the JavaScript configuration for you. Reading this manual is still useful, because all YAML keys map one-to-one to the API names described below.

Modules

Swiper is built from a core and a set of optional modules. Each module adds a feature (navigation arrows, pagination dots, autoplay, zoom, etc.) and can be turned on or off independently. The J1 bundle (swiper-bundle.js) ships with all of the modules below pre-registered, so you only need to enable them in the parameters.

Name Description

Accessibility (a11y)

Once the a11y (Accessibility) module is activated, Swiper automatically adds ARIA attributes and semantic roles to the DOM. Specifically, important ARIA attributes such as aria-live, aria-label, and role are automatically added to the slider and its controls so that screen reader users can understand the purpose of the slider and navigate between the slides.

Virtual

Keeps only the slides that are currently visible (plus a small buffer) in the DOM and removes all others. Use this when your slider has many slides or very heavy content. The page stays fast because the browser does not have to render slides the visitor cannot see.

Keyboard

Lets visitors move between slides with the left and right (or up/down) arrow keys. Useful on desktop, for accessibility, and for keyboard-only users. You can limit the keys to the slider area only (onlyInViewport).

Mousewheel

Turns the mouse wheel (or two-finger touchpad scroll) into a slide control. Scrolling down or right moves to the next slide; scrolling up or left moves to the previous one. Helpful for full-screen slideshows on desktop.

Navigation

Adds two navigation buttons ("previous" and "next") next to the slider. Visitors click them to jump one slide back or forward. You can style the buttons with CSS or replace them with your own elements.

Pagination

Shows pagination indicators below (or beside) the slider so visitors can see how many slides exist and which one is active. The default is a row of bullets; you can also choose fraction ("3 / 10"), progressbar, or a fully custom renderer.

Scrollbar

Adds a small scrollbar under (or beside) the slider that reflects the current position. The scrollbar can be set to be draggable so the visitor can use it like a thumb to scrub through the slides.

Parallax

Lets you move parts of a slide at a different speed than the slide itself. The result is a sense of depth: a background image moves slowly while the headline in front moves faster. Parallax is configured per element with data-swiper-parallax attributes.

Zoom

Allows the visitor to zoom into the active slide by double-tapping (touch) or double-clicking (mouse), and to pan the zoomed image with a finger or the mouse. Useful for product galleries and photo viewers.

Controller

Connects two or more Swipers so that one drives the other(s). When the master slider moves, the slaves follow. This is the basis for thumbnail strips and side-by-side comparison sliders.

History

Updates the browser’s URL and history whenever the active slide changes. Each slide can have its own URL, so visitors can bookmark or share a direct link to a specific slide and the back/forward buttons work as expected.

HashNavigation

Like History, but uses the URL hash fragment (the part after #) instead of a full URL path. Lighter to set up because it does not need server-side rewriting. The hash is updated when the active slide changes.

Autoplay

Moves the slider forward automatically on a timer (default 3 seconds per slide). Autoplay can be paused on hover, stopped on the last slide, or disabled after the first user interaction.

Thumb

A pre-wired combination of Controller and a second small Swiper that shows thumbnail previews. Click a thumbnail and the main slider jumps to the matching slide; swipe the main slider and the active thumbnail follows.

Free Mode

Disables the snap-to-slide behaviour so the slider can stop between slides. Useful for continuous content like long image strips or product rows where snapping to a fixed slide would feel wrong.

Grid

Lets a slider show multiple rows of slides at the same time. You set the number of rows with grid.rows; Swiper then fills them column by column from left to right (or top to bottom in vertical sliders).

Manipulation

Adds methods for adding, removing, prepending or appending slides at runtime from JavaScript. Without this module, the slide list is fixed once the slider is created.

Transition Effects

A family of modules that change how the active slide is replaced by the next one. The default is a horizontal slide; alternatives are fade, cube, flip, coverflow, creative and cards. Each effect has its own options object (e.g. fadeEffect, cubeEffect).

Features

The available modules result in the following key features:

Name Description

Slide navigation

Swiping, arrow keys, mouse wheel, buttons (swiper-button-prev | swiper-button-next), pagination, scrollbar.

Hardware-accelerated transitions

Controlled via CSS transforms (translate3d), including special effects such as fade, cube, flip, coverflow, creative and cards.

Modes

Loop and free mode, autoplay, rewind.

Responsiveness

Responsive behaviour with breakpoints and grid layout (multiple rows).

Accessibility (A11y)

Adds ARIA attributes and semantic roles to the slider and its controls so that screen-reader users can understand the purpose of the slider and navigate between the slides.

Deep linking

History or Hash navigation lets every slide have its own URL, so a visitor can bookmark or share a direct link to a specific slide.

Mobile-friendly

Intended to be used in mobile websites, mobile web apps, and mobile native/hybrid apps.

Library Agnostic

Swiper doesn’t require any JavaScript libraries like jQuery, which makes Swiper much smaller and faster. It can be safely used with libraries such as jQuery, Zepto, jQuery Mobile, etc.

1:1 Touch movement

By default, Swiper provides 1:1 touch movement interaction, but this ratio can be configured through Swiper settings.

Mutation Observer

Swiper has an option to enable Mutation Observer. With this feature, Swiper will be automatically reinitialised and recalculate all required parameters if you make dynamic changes to the DOM, or to Swiper styles themselves.

RTL

Swiper is the only slider that provides 100% RTL support with correct layout.

Multi Row Slides Layout

Swiper allows a multiple-row slides layout, with a few slides per column.

Transition Effects

Fade, Flip, 3D Cube, 3D Coverflow.

Two-way Control

Swiper may be used as controller for any number of other Swipers, and even be controlled at the same time.

Full Navigation Control

Swiper comes with all required built-in navigation elements, such as Pagination, Navigation arrows and Scrollbar.

Flexbox Layout

Swiper uses modern flexbox layout for slides layout, which solves a lot of problems and time with size calculations. Such layout also allows configuring the Slides grid using pure CSS.

Most Flexible Slides Layout Grid

Swiper has a lot of parameters on initialisation to make it as flexible as possible. You can control slides per view, per column, per group, space between slides, and many more.

Lazy Loading Images

Swiper Lazy Loading delays loading of images in inactive/invisible slides until the user swipes to them. Such a feature can make the page load faster and improve Swiper performance.

Virtual Slides

Swiper comes with the Virtual Slides feature that is great when you have a lot of slides or content-heavy/image-heavy slides, so it will keep just the required amount of slides in the DOM.

CSS styles

Swiper CSS comes in two flavours: a bundle (one file, everything included) and single-module files (one per feature). In the J1 Template the bundle is used by default (swiper-bundle.css), so you do not have to import individual module CSS files.

CSS styles for the bundle version:

  • swiper-bundle.css — all Swiper styles including all module styles (Navigation, Pagination, etc.)

  • swiper-bundle.min.css — same as previous but minified

CSS styles for the bundle version (package imports):

  • swiper/css — all Swiper styles including all module styles (Navigation, Pagination, etc.)

  • swiper/css/bundle — same as previous but minified

CSS styles for the core version and individual modules (package imports):

  • swiper/css — only core Swiper styles

  • swiper/css/a11y — styles required for the A11y module

  • swiper/css/autoplay — styles required for the Autoplay module

  • swiper/css/controller — styles required for the Controller module

  • swiper/css/effect-cards — styles required for the Cards Effect module

  • swiper/css/effect-coverflow — styles required for the Coverflow Effect module

  • swiper/css/effect-creative — styles required for the Creative Effect module

  • swiper/css/effect-cube — styles required for the Cube Effect module

  • swiper/css/effect-fade — styles required for the Fade Effect module

  • swiper/css/effect-flip — styles required for the Flip Effect module

  • swiper/css/free-mode — styles required for the Free Mode module

  • swiper/css/grid — styles required for the Grid module

  • swiper/css/hash-navigation — styles required for the Hash Navigation module

  • swiper/css/history — styles required for the History module

  • swiper/css/keyboard — styles required for the Keyboard module

  • swiper/css/manipulation — styles required for the Manipulation module

  • swiper/css/mousewheel — styles required for the Mousewheel module

  • swiper/css/navigation — styles required for the Navigation module

  • swiper/css/pagination — styles required for the Pagination module

  • swiper/css/parallax — styles required for the Parallax module

  • swiper/css/scrollbar — styles required for the Scrollbar module

  • swiper/css/thumbs — styles required for the Thumbs module

  • swiper/css/virtual — styles required for the Virtual module

  • swiper/css/zoom — styles required for the Zoom module

HTML Layout

A Swiper slider is built from a few required HTML elements and several optional helpers. The required ones are the main container (.swiper), the wrapper (.swiper-wrapper) and one or more slides (.swiper-slide). The optional helpers are pagination, navigation buttons and the scrollbar; they only appear if you turn the matching module on in the parameters.

<!-- Slider main container -->
<div class="swiper">
  <!-- Additional required wrapper -->
  <div class="swiper-wrapper">
    <!-- Slides -->
    <div class="swiper-slide">Slide 1</div>
    <div class="swiper-slide">Slide 2</div>
    <div class="swiper-slide">Slide 3</div>
    ...
  </div>
  <!-- If we need pagination -->
  <div class="swiper-pagination"></div>
  <!-- If we need navigation buttons -->
  <div class="swiper-button-prev"></div>
  <div class="swiper-button-next"></div>
  <!-- If we need scrollbar -->
  <div class="swiper-scrollbar"></div>
</div>

In J1 Template you normally do not write this markup yourself. The swiper adapter loads the slider HTML from an Asciidoc fragment configured under xhr_data_path and inserts it into a placeholder on the page (see the AsciiDoc extension swiper::). The pattern above is what the adapter expects to find in that fragment.

Initialization

When the Swiper’s HTML portion is in place, we need to initialise it like so:

new Swiper(swiperContainer, parameters) // initialize swiper with options
  • swiperContainer — HTMLElement or string (with CSS selector) of the swiper container HTML element. Required.

  • parameters — object with Swiper parameters. Optional.

  • The constructor returns the initialised Swiper instance.

Example
const mySwiper = new Swiper('.my-swiper-container', {
  speed:        400,
  spaceBetween: 100,
});

After you initialise Swiper, it is possible to access Swiper’s instance on its HTMLElement. It is the swiper property of Swiper’s HTML container element:

const swiperInstance = document.querySelector('.my-swiper-container').swiper;
// Now you can use all slider methods like
swiperInstance.slideNext();

Initialisation in J1 Template

In a J1 site the call above is generated by the swiper adapter from your YAML configuration

The adapter:

  1. waits until the page is fully loaded and the slider’s HTML fragment has been injected,

  2. reads the parameters from the YAML configuration of each slider,

  3. calls new Swiper(…​) for every enabled slider,

  4. optionally creates a PhotoSwipe Lightbox on top of the slider when lightbox.enabled is set.

You can still grab the resulting instance from JavaScript via document.querySelector('#<your_swiper_id>').swiper and call any of the methods listed further down on this page.

Parameters

The SwiperJS API offers a rich collection of parameters that allow you to configure almost every aspect of a slider. A parameter is just a key/value pair you pass as the second argument to the Swiper constructor (or, in J1 Template, write under the parameters: key of the slider’s YAML configuration).

Initialization example
const mySwiper = new Swiper('.my-swiper-container', {
  speed:        400,
  spaceBetween: 100,
});

This section lists all available parameters in alphabetical order. Each parameter gets its own subsection with a short description and, where helpful, a code example. The accepted value types and the default value are summarised in a small table at the end of each subsection.

a11y

Once the a11y (Accessibility) module is activated, Swiper automatically adds ARIA attributes and semantic roles to the DOM. Specifically, important ARIA attributes such as aria-live, aria-label, and role are automatically added to the slider and its controls so that screen reader users can understand the purpose of the slider and navigate between the slides.

Object with a11y parameters or boolean true to enable with default settings.

const mySwiper = new Swiper('.my-swiper-container', {
  a11y: {
    prevSlideMessage: 'Previous slide',
    nextSlideMessage: 'Next slide',
  },
});
Name Type Default

a11y

boolean | A11yOptions

none

allowSlideNext

Set to false to disable swiping to the next-slide direction (to the right, or to the bottom for vertical sliders).

Name Type Default

allowSlideNext

boolean

true

allowSlidePrev

Set to false to disable swiping to the previous-slide direction (to the left, or to the top for vertical sliders).

Name Type Default

allowSlidePrev

boolean

true

allowTouchMove

Set to false to disable touch/mouse dragging. The only way to switch slides is then through external API calls such as slidePrev() or slideNext().

Name Type Default

allowTouchMove

boolean

true

autoHeight

When set to true, the slider wrapper will adapt its height to the height of the currently active slide. Useful for sliders whose slides have different heights (for example, slides with images and slides with long text).

Name Type Default

autoHeight

boolean

false

autoplay

Object with autoplay parameters or boolean true to enable with default settings.

const swiper = new Swiper('.swiper', {
 autoplay: {
   delay: 5000,
 },
});
Name Type Default

autoplay

boolean | AutoplayOptions

none

breakpoints

Allows setting different parameters for different responsive breakpoints (screen sizes). Not all parameters can be changed in breakpoints — only those that do not require a different layout or different logic, such as slidesPerView, slidesPerGroup, spaceBetween, and grid.rows.

Parameters like loop and effect won’t work inside breakpoints.

const swiper = new Swiper('.swiper', {
  // Default parameters
  slidesPerView: 1,
  spaceBetween:  10,
  // Responsive breakpoints
  breakpoints: {
    // when window width is >= 320px
    320: {
      slidesPerView: 2,
      spaceBetween:  20
    },
    // when window width is >= 480px
    480: {
      slidesPerView: 3,
      spaceBetween:  30
    },
    // when window width is >= 640px
    640: {
      slidesPerView: 4,
      spaceBetween:  40
    }
  }
})
const swiper = new Swiper('.swiper', {
  slidesPerView: 1,
  spaceBetween:  10,
  // using "ratio" endpoints
  breakpoints: {
    '@0.75': {
      slidesPerView: 2,
      spaceBetween:  20,
    },
    '@1.00': {
      slidesPerView: 3,
      spaceBetween:  40,
    },
    '@1.50': {
      slidesPerView: 4,
      spaceBetween:  50,
    },
  }
});
Name Type Default

breakpoints

object

none

breakpointsBase (beta)

Base for breakpoints. Can be window or container. If set to window (by default) then breakpoint keys mean window width. If set to container then breakpoint keys are treated as the swiper container width.

Name Type Default

breakpointsBase

CSSSelector | container | window

window

cardsEffect

Object with Cards-effect parameters.

const swiper = new Swiper('.swiper', {
  effect: 'cards',
  cardsEffect: {
    // ...
  },
});
Name Type Default

cardsEffect

CardsEffectOptions

none

centerInsufficientSlides

When enabled, centers slides if the number of slides is less than slidesPerView.

Not intended to be used with loop mode and grid.rows.

Name Type Default

centerInsufficientSlides

boolean

false

centeredSlides

When set to true, the active slide will be centred — not always on the left side.

Name Type Default

centeredSlides

boolean

false

centeredSlidesBounds

When set to true, the active slide will be centred without adding gaps at the beginning and end of the slider. Requires centeredSlides: true.

Not intended to be used with loop or pagination.

Name Type Default

centeredSlidesBounds

boolean

false

containerModifierClass

The beginning (prefix) of the modifier CSS class that can be added to the swiper container depending on different parameters.

Name Type Default

containerModifierClass

string

'swiper-'

controller

Object with controller parameters or boolean true to enable with default settings.

const swiper = new Swiper('.swiper', {
  controller: {
    inverse: true,
  },
});
Name Type Default

controller

ControllerOptions | boolean

none | true

coverflowEffect

Object with Coverflow-effect parameters.

const swiper = new Swiper('.swiper', {
  effect: 'coverflow',
  coverflowEffect: {
    rotate:       30,
    slideShadows: false,
  },
});
Name Type Default

coverflowEffect

CoverflowEffectOptions

none

createElements

When enabled, Swiper will automatically wrap slides with a swiper-wrapper element and create the required elements for navigation, pagination and scrollbar when they are enabled (with their respective params object or with boolean true).

Name Type Default

createElements

boolean

false

creativeEffect

Object with Creative-effect parameters.

const swiper = new Swiper('.swiper', {
  effect: 'creative',
  creativeEffect: {
    prev: {
      // will set `translateZ(-400px)` on previous slides
      translate: [0, 0, -400],
    },
    next: {
      // will set `translateX(100%)` on next slides
      translate: ['100%', 0, 0],
    },
  },
});
Name Type Default

creativeEffect

CreativeEffectOptions

none

cssMode

When enabled, Swiper will use the modern CSS Scroll Snap API. It doesn’t support all of Swiper’s features, but should potentially bring much better performance in simple configurations.

The following features are not supported when cssMode is enabled:

  • Cube effect

  • speed parameter may have no effect

  • All transition start/end related events (use slideChange instead)

  • slidesPerGroup has limited support

  • simulateTouch doesn’t have effect and "dragging" with the mouse doesn’t work

  • resistance doesn’t have any effect

  • allowSlidePrev / allowSlideNext

  • swipeHandler

If you use cssMode together with other effects (especially 3D effects), wrap each slide’s content in a <div class="swiper-slide-transform"> element. Any custom styles on slides (background colours, border radius, borders, etc.) should also be set on swiper-slide-transform instead of on swiper-slide.

<div class="swiper">
  <div class="swiper-wrapper">
    <div class="swiper-slide">
      <!-- wrap slide content with transform element -->
      <div class="swiper-slide-transform">
        ... slide content ...
      </div>
    </div>
    ...
  </div>
</div>
<script>
const swiper = new Swiper('.swiper', {
   effect:  'flip',
   cssMode: true,
 });
</script>
Name Type Default

cssMode

boolean

false

cubeEffect

Object with Cube-effect parameters.

const swiper = new Swiper('.swiper', {
  effect: 'cube',
  cubeEffect: {
    slideShadows: false,
  },
});
Name Type Default

cubeEffect

CubeEffectOptions

none

direction

Can be horizontal or vertical (for a vertical slider).

Name Type Default

direction

'horizontal' | 'vertical'

horizontal

edgeSwipeDetection

Enable to release Swiper events for swipe-back work in app. When set to prevent, it will prevent system swipe-back navigation instead.

This feature works only with "touch" events (and not pointer events), so it will work on iOS/Android devices and won’t work on Windows devices with pointer events.

Name Type Default

edgeSwipeDetection

string | boolean

false

edgeSwipeThreshold

Area (in px) from the left edge of the screen where touch events are released for swipe-back in app.

Name Type Default

edgeSwipeThreshold

number

20

effect

Transition effect. Can be one of slide, fade, cube, coverflow, flip, creative or cards.

Name Type Default

effect

string

'slide'

enabled

Whether Swiper is initially enabled. When Swiper is disabled, it will hide all navigation elements and won’t respond to any events or interactions.

Name Type Default

enabled

boolean

true

eventsPrefix

Event name prefix for all DOM events emitted by Swiper Element (web component).

Name Type Default

eventsPrefix

string

'swiper'

fadeEffect

Object with Fade-effect parameters.

const swiper = new Swiper('.swiper', {
  effect: 'fade',
  fadeEffect: {
    crossFade: true
  },
});
Name Type Default

fadeEffect

FadeEffectOptions

none

flipEffect

Object with Flip-effect parameters.

const swiper = new Swiper('.swiper', {
  effect: 'flip',
  flipEffect: {
    slideShadows: false,
  },
});
Name Type Default

flipEffect

FlipEffectOptions

none

focusableElements

CSS selector for focusable elements. Swiping will be disabled on such elements when they are "focused" (for example, a <select> inside a slide will receive keyboard input instead of triggering a slide change).

Name Type Default

focusableElements

string

'input, select, option, textarea, button, video, label'

followFinger

If disabled, the slider will be animated only when you release it; it will not move while you hold your finger on it.

Name Type Default

followFinger

boolean

true

freeMode

Enables free-mode functionality. Object with free-mode parameters or boolean true to enable with default settings.

const swiper = new Swiper('.swiper', {
  freeMode: true,
});
const swiper = new Swiper('.swiper', {
  freeMode: {
    enabled: true,
    sticky:  true,
  },
});
Name Type Default

freeMode

boolean | FreeModeOptions

none

grabCursor

May slightly improve desktop usability. If true, the user will see the "grab" cursor when hovering over Swiper.

Name Type Default

grabCursor

boolean

false

grid

Object with grid parameters to enable a "multi-row" slider.

const swiper = new Swiper('.swiper', {
  grid: {
    rows: 2,
  },
});
Name Type Default

grid

GridOptions

none

hashNavigation

Enables hash-URL navigation for slides. Object with hash-navigation parameters or boolean true to enable with default settings.

const swiper = new Swiper('.swiper', {
  hashNavigation: {
    replaceState: true,
  },
});
Name Type Default

hashNavigation

boolean | HashNavigationOptions

none

height

Swiper height (in px). Allows you to force the Swiper height. Useful only when you initialise Swiper when it is hidden, and in SSR and test environments, for correct Swiper initialisation.

Setting this parameter will make Swiper not responsive.

Name Type Default

height

number | null

null

history

Enables history push-state so every slide can have its own URL. With this parameter you specify the main slides URL like "slides" and specify every slide’s URL using the data-history attribute.

Object with history-navigation parameters or boolean true to enable with default settings.

const swiper = new Swiper('.swiper', {
  history: {
    replaceState: true,
  },
});
<!-- will produce "slides/slide1" url in browser history -->
<div class="swiper-slide" data-history="slide1"></div>
Name Type Default

history

boolean | HistoryOptions

none

init

Whether Swiper should be initialised automatically when you create an instance. If disabled, you need to init it manually by calling swiper.init().

Name Type Default

init

boolean

true

initialSlide

Index number of the initial slide.

Name Type Default

initialSlide

number

0

injectStyles

Inject text styles into the shadow DOM. Only for usage with Swiper Element (web component).

Name Type Default

injectStyles

string[]

none

injectStylesUrls

Inject styles <link> tags into the shadow DOM. Only for usage with Swiper Element (web component).

Name Type Default

injectStylesUrls

string[]

none

keyboard

Enables navigation through slides using the keyboard. Object with keyboard parameters or boolean true to enable with default settings.

const swiper = new Swiper('.swiper', {
  keyboard: {
    enabled:        true,
    onlyInViewport: false,
  },
});
Name Type Default

keyboard

boolean | KeyboardOptions

none

lazyPreloadPrevNext

Number of next and previous slides to preload. Only applicable when using lazy loading.

Name Type Default

lazyPreloadPrevNext

number

0

lazyPreloaderClass

CSS class name of the lazy preloader.

Name Type Default

lazyPreloaderClass

string

'swiper-lazy-preloader'

longSwipes

Set to false to disable long swipes.

Name Type Default

longSwipes

boolean

true

longSwipesMs

Minimum duration (in ms) to trigger a swipe to the next/previous slide during long swipes.

Name Type Default

longSwipesMs

number

300

longSwipesRatio

Ratio to trigger a swipe to the next/previous slide during long swipes.

Name Type Default

longSwipesRatio

number

0.5

loop

Set to true to enable continuous loop mode.

Because of how loop mode works (it rearranges slides), the total number of slides must be:

  • more than or equal to slidesPerView + slidesPerGroup (and + 1 in case of centeredSlides)

  • a multiple of slidesPerGroup (or use loopAddBlankSlides)

  • a multiple of grid.rows (or use loopAddBlankSlides)

Name Type Default

loop

boolean

false

loopAddBlankSlides

Automatically adds blank slides if you use Grid or slidesPerGroup and the total number of slides is not a multiple of slidesPerGroup or grid.rows.

Name Type Default

loopAddBlankSlides

boolean

true

loopAdditionalSlides

Allows you to increase the amount of looped slides.

Name Type Default

loopAdditionalSlides

number

0

loopPreventsSliding

If enabled, slideNext / slidePrev will do nothing while the slider is animating in loop mode.

Name Type Default

loopPreventsSliding

boolean

true

maxBackfaceHiddenSlides

If the total number of slides is less than the value specified here, Swiper will enable backface-visibility: hidden on slide elements to reduce visual "flicker" in Safari.

It is not recommended to enable this on a large number of slides because it will reduce performance.

Name Type Default

maxBackfaceHiddenSlides

number

10

modules

Array of Swiper modules. Use this option to attach optional Swiper modules (such as Navigation, Pagination, Keyboard, etc.) when you import Swiper as ES modules.

import Swiper from 'swiper';
import { Navigation, Pagination } from 'swiper/modules';
const swiper = new Swiper('.swiper', {
  modules: [ Navigation, Pagination ],
});
Name Type Default

modules

SwiperModule[]

none

mousewheel

Enables navigation through slides using the mouse wheel. Object with mousewheel parameters or boolean true to enable with default settings.

const swiper = new Swiper('.swiper', {
  mousewheel: {
    invert: true,
  },
});
Name Type Default

mousewheel

boolean | MousewheelOptions

none

navigation

Object with navigation parameters or boolean true to enable with default settings.

const swiper = new Swiper('.swiper', {
  navigation: {
    nextEl: '.swiper-button-next',
    prevEl: '.swiper-button-prev',
  },
});
Name Type Default

navigation

boolean | NavigationOptions

none

nested

Set to true on the inner Swiper for correct touch-events interception. Use only on swipers that move in the same direction as the parent.

Name Type Default

nested

boolean

false

noSwiping

Enable/disable swiping on elements that match the class specified in noSwipingClass.

Name Type Default

noSwiping

boolean

true

noSwipingClass

CSS class for noSwiping elements.

Name Type Default

noSwipingClass

string

'swiper-no-swiping'

noSwipingSelector

Can be used instead of noSwipingClass to specify elements to disable swiping on. For example, input will disable swiping on all input fields.

Name Type Default

noSwipingSelector

string

none

normalizeSlideIndex

Normalise the slide index.

Name Type Default

normalizeSlideIndex

boolean

true

observeParents

Set to true if you also need to watch mutations on Swiper parent elements.

Name Type Default

observeParents

boolean

false

observeSlideChildren

Set to true if you also need to watch mutations on Swiper slide children elements.

Name Type Default

observeSlideChildren

boolean

false

observer

Set to true to enable Mutation Observer on Swiper and its elements. In this case Swiper will be updated (re-initialised) each time you change its style (such as hide/show) or modify its child elements (such as adding or removing slides).

Name Type Default

observer

boolean

false

on

Register event handlers. Pass an object whose keys are Swiper event names and whose values are the handler functions to invoke when those events fire.

Name Type Default

on

object

none

onAny

Add an event listener that will be fired on all events.

const swiper = new Swiper('.swiper', {
  onAny(eventName, ...args) {
    console.log('Event: ',      eventName);
    console.log('Event data: ', args);
  }
});
Name Type Default

onAny

function(handler)

none

oneWayMovement

When enabled, slides will only swipe forward (one way) regardless of the swipe direction.

Name Type Default

oneWayMovement

boolean

false

pagination

Object with pagination parameters or boolean true to enable with default settings.

const swiper = new Swiper('.swiper', {
  pagination: {
    el:   '.swiper-pagination',
    type: 'bullets',
  },
});
Name Type Default

pagination

boolean | PaginationOptions

none

parallax

Object with parallax parameters or boolean true to enable with default settings.

const swiper = new Swiper('.swiper', {
  parallax: true,
});
Name Type Default

parallax

boolean | ParallaxOptions

none

passiveListeners

Passive event listeners are used by default where possible to improve scrolling performance on mobile devices. If you need to use e.preventDefault and have a conflict with it, you should disable this parameter.

Name Type Default

passiveListeners

boolean

true

preventClicks

Set to true to prevent accidental unwanted clicks on links during swiping.

Name Type Default

preventClicks

boolean

true

preventClicksPropagation

Set to true to stop click-event propagation on links during swiping.

Name Type Default

preventClicksPropagation

boolean

true

preventInteractionOnTransition

When enabled, it won’t allow you to change slides by swiping or by navigation/pagination buttons during a transition.

Name Type Default

preventInteractionOnTransition

boolean

false

resistance

Set to false if you want to disable resistant bounds.

Name Type Default

resistance

boolean

true

resistanceRatio

Controls the resistance ratio.

Name Type Default

resistanceRatio

number

0.85

resizeObserver

When enabled, Swiper will use ResizeObserver (if supported by the browser) on the swiper container to detect container resize (instead of watching for window resize).

Name Type Default

resizeObserver

boolean

true

rewind

Set to true to enable "rewind" mode. When enabled, clicking the "next" navigation button (or calling .slideNext()) on the last slide will slide back to the first slide. Clicking "prev" (or calling .slidePrev()) on the first slide will slide forward to the last slide.

Should not be used together with loop mode.

Name Type Default

rewind

boolean

false

roundLengths

Set to true to round the values of slide width and height to prevent blurry text on usual-resolution screens (if you have such).

Name Type Default

roundLengths

boolean

false

runCallbacksOnInit

Fire Transition/SlideChange/Start/End events on Swiper initialisation. Such events will be fired on initialisation when your initialSlide is not 0, or when you use loop mode.

Name Type Default

runCallbacksOnInit

boolean

true

scrollbar

Object with scrollbar parameters or boolean true to enable with default settings.

const swiper = new Swiper('.swiper', {
  scrollbar: {
    el:        '.swiper-scrollbar',
    draggable: true,
  },
});
Name Type Default

scrollbar

boolean | ScrollbarOptions

none

setWrapperSize

Enable this option and the plugin will set width/height on the swiper wrapper equal to the total size of all slides. Mostly used as a compatibility fallback for browsers that don’t support flexbox layout well.

Name Type Default

setWrapperSize

boolean

false

shortSwipes

Set to false to disable short swipes.

Name Type Default

shortSwipes

boolean

true

simulateTouch

If true, Swiper will accept mouse events like touch events (click and drag to change slides).

Name Type Default

simulateTouch

boolean

true

slideActiveClass

CSS class name of the currently active slide.

By changing classes you will also need to change Swiper’s CSS to reflect the changed classes.

Name Type Default

slideActiveClass

string

'swiper-slide-active'

slideBlankClass

CSS class name of the blank slide added by loop mode (when loopAddBlankSlides is enabled).

Name Type Default

slideBlankClass

string

'swiper-slide-blank'

slideClass

CSS class name of a slide.

By changing classes you will also need to change Swiper’s CSS to reflect the changed classes.

Name Type Default

slideClass

string

'swiper-slide'

slideFullyVisibleClass

CSS class name of a fully visible slide (when the whole slide is in the viewport).

Name Type Default

slideFullyVisibleClass

string

'swiper-slide-fully-visible'

slideNextClass

CSS class name of the slide that is right after the currently active slide.

By changing classes you will also need to change Swiper’s CSS to reflect the changed classes.

Name Type Default

slideNextClass

string

'swiper-slide-next'

slidePrevClass

CSS class name of the slide that is right before the currently active slide.

By changing classes you will also need to change Swiper’s CSS to reflect the changed classes.

Name Type Default

slidePrevClass

string

'swiper-slide-prev'

slideToClickedSlide

Set to true and a click on any slide will produce a transition to that slide.

Name Type Default

slideToClickedSlide

boolean

false

slideVisibleClass

CSS class name of a currently/partially visible slide.

By changing classes you will also need to change Swiper’s CSS to reflect the changed classes.

Name Type Default

slideVisibleClass

string

'swiper-slide-visible'

slidesOffsetAfter

Add (in px) additional slide offset at the end of the container (after all slides).

Name Type Default

slidesOffsetAfter

number

0

slidesOffsetBefore

Add (in px) additional slide offset at the beginning of the container (before all slides).

Name Type Default

slidesOffsetBefore

number

0

slidesPerGroup

Set the number of slides to define and enable group sliding. Useful with slidesPerView > 1.

Name Type Default

slidesPerGroup

number

1

slidesPerGroupAuto

Intended to be used only with slidesPerView: 'auto' and slidesPerGroup: 1. When enabled, it will skip all slides in view on .slideNext() and .slidePrev() method calls, on Navigation "buttons" clicks, and during autoplay.

Name Type Default

slidesPerGroupAuto

boolean

false

slidesPerGroupSkip

The parameter works in the following way: if slidesPerGroupSkip equals 0 (default), no slides are excluded from grouping, and the resulting behaviour is the same as without this change.

If slidesPerGroupSkip is equal to or greater than 1, the first X slides are treated as single groups, whereas all following slides are grouped by the slidesPerGroup value.

Name Type Default

slidesPerGroupSkip

number

0

slidesPerView

Number of slides per view (slides visible at the same time on the slider’s container).

slidesPerView: 'auto' is currently not compatible with multi-row mode (when grid.rows > 1).

Name Type Default

slidesPerView

number | 'auto'

1

snapToSlideEdge

When enabled, the swiper will always snap to slide edges rather than arbitrary positions. This prevents partial slides from appearing misaligned at the end of the swiper. Only applies when slidesPerView is fractional or auto, and is ignored in loop and centeredSlides modes.

Name Type Default

snapToSlideEdge

boolean

false

spaceBetween

Distance between slides in px.

If you use a margin CSS property on the elements that go into Swiper, and at the same time pass spaceBetween, navigation might not work properly.

Name Type Default

spaceBetween

string | number

0

speed

Duration of the transition between slides (in ms).

Name Type Default

speed

number

300

swipeHandler

String with the CSS selector or HTML element of the container with pagination that will work as the only available handler for swiping.

Name Type Default

swipeHandler

HTMLElement | CSSSelector | null

null

swiperElementNodeName

The name of the swiper-element node; used for detecting web-component rendering.

Name Type Default

swiperElementNodeName

string

'SWIPER-CONTAINER'

threshold

Threshold value in px. If the "touch distance" is lower than this value, swiper will not move.

Name Type Default

threshold

number

5

thumbs

Object with thumbs-component parameters. Used to control a separate "thumbnails" Swiper instance that drives the main slider.

const swiper = new Swiper('.swiper', {
  thumbs: {
    swiper: thumbsSwiper
  }
});
Name Type Default

thumbs

ThumbsOptions

none

touchAngle

Allowable angle (in degrees) to trigger a touch move.

Name Type Default

touchAngle

number

45

touchEventsTarget

Target element to listen for touch events on. Can be container (to listen for touch events on the swiper) or wrapper (to listen for touch events on the swiper-wrapper).

Name Type Default

touchEventsTarget

'container' | 'wrapper'

wrapper

touchMoveStopPropagation

If enabled, propagation of touchmove will be stopped.

Name Type Default

touchMoveStopPropagation

boolean

false

touchRatio

Touch ratio. A value greater than 1 makes slides follow the finger faster than the actual movement, a value lower than 1 makes them follow more slowly.

Name Type Default

touchRatio

number

1

touchReleaseOnEdges

Enable to release touch events at the slider edge position (beginning, end) to allow for further page scrolling.

This feature works only with "touch" events (and not pointer events), so it will work on iOS/Android devices and won’t work on Windows devices with pointer events. The threshold parameter must also be set to 0.

Name Type Default

touchReleaseOnEdges

boolean

false

touchStartForcePreventDefault

Force to always prevent default for touchstart (pointerdown) events.

Name Type Default

touchStartForcePreventDefault

boolean

false

touchStartPreventDefault

If disabled, the pointerdown event won’t be prevented.

Name Type Default

touchStartPreventDefault

boolean

true

uniqueNavElements

If enabled (by default) and navigation-element parameters are passed as a string (such as ".pagination"), Swiper will look for such elements among child elements first. Applies to pagination, prev/next buttons and scrollbar elements.

Name Type Default

uniqueNavElements

boolean

true

updateOnWindowResize

Swiper will recalculate slides position on window resize (orientationchange).

Name Type Default

updateOnWindowResize

boolean

true

url

Required for active-slide detection when rendered on server-side and when history is enabled.

Name Type Default

url

string | null

null

userAgent

userAgent string. Required for browser/device detection when rendered on server-side.

Name Type Default

userAgent

string | null

null

virtual

Enables virtual-slides functionality. Object with virtual-slides parameters or boolean true to enable with default settings.

const swiper = new Swiper('.swiper', {
  virtual: {
    slides: ['Slide 1', 'Slide 2', 'Slide 3', 'Slide 4', 'Slide 5'],
  },
});
Name Type Default

virtual

boolean | VirtualOptions

none

virtualTranslate

Enable this option and Swiper will be operated as usual except that it will not move — real translate values on the wrapper will not be set. Useful when you need to create a custom slide transition.

Name Type Default

virtualTranslate

boolean

false

watchOverflow

When enabled, Swiper will be disabled and hide navigation buttons in case there are not enough slides for sliding.

Name Type Default

watchOverflow

boolean

true

watchSlidesProgress

Enable this feature to calculate each slide’s progress and visibility (slides in the viewport will have an additional visible class).

Name Type Default

watchSlidesProgress

boolean

false

width

Swiper width (in px). Allows you to force the Swiper width. Useful only when you initialise Swiper while it is hidden, and in SSR and test environments, for correct Swiper initialisation.

Setting this parameter will make Swiper not responsive.

Name Type Default

width

number | null

null

wrapperClass

CSS class name of the slides' wrapper.

By changing classes you will also need to change Swiper’s CSS to reflect the changed classes.

Name Type Default

wrapperClass

string

'swiper-wrapper'

zoom

Enables zooming functionality. Object with zoom parameters or boolean true to enable with default settings.

const swiper = new Swiper('.swiper', {
  zoom: {
    maxRatio: 5,
  },
});
Name Type Default

zoom

boolean | ZoomOptions

none

Properties

A property is a value that Swiper exposes on the slider instance. You read it the same way you read a field on any JavaScript object:

const mySwiper = new Swiper('.swiper');
console.log(mySwiper.activeIndex);   // 0, 1, 2, ...
console.log(mySwiper.isEnd);         // true / false

In the J1 Template the instance is also available on the slider’s HTML element as the swiper property of that element:

const slider = document.querySelector('#my-swiper').swiper;
console.log(slider.activeIndex);

The table below lists all properties available on the Swiper instance in alphabetical order.

Name Type Description

swiper.activeIndex

number

Index number of the currently active slide.

Note: in loop mode the active index is always shifted by the number of looped (cloned) slides. Use swiper.realIndex to get the index of the original slide.

swiper.allowSlideNext

boolean

Enable or disable swiping to the next slide. Set this property to false to lock the next direction, true to unlock it.

swiper.allowSlidePrev

boolean

Enable or disable swiping to the previous slide. Set this property to false to lock the previous direction, true to unlock it.

swiper.allowTouchMove

boolean

Enable or disable moving the slider by grabbing it with the mouse or by touching it with a finger (on touch screens). Set false to disable, true to enable.

swiper.animating

boolean

true while the slider is in transition between two slides, false otherwise.

swiper.clickedIndex

number

Index number of the slide that was clicked or tapped last.

swiper.clickedSlide

HTMLElement

Reference to the HTML element of the slide that was clicked or tapped last.

swiper.defaults

SwiperOptions

Object with Swiper’s built-in default options (before any of your parameters are merged in).

swiper.el

HTMLElement

HTML element of the slider container (the element with the swiper CSS class).

swiper.enabled

boolean

true if Swiper is currently enabled, false otherwise (see enable() / disable() methods).

swiper.extendedDefaults

SwiperOptions

Object with globally extended Swiper defaults (as set via Swiper.extendDefaults(…​)).

swiper.height

number

Current height of the slider container (in pixels).

swiper.isBeginning

boolean

true when the slider is on its first slide (left/top edge).

swiper.isEnd

boolean

true when the slider is on its last slide (right/bottom edge).

swiper.isLocked

boolean

true when the slider is locked by watchOverflow and can no longer slide (for example when there are fewer slides than slidesPerView).

swiper.originalParams

SwiperOptions

Object with the original initialization parameters (exactly the object you passed into new Swiper(…​)).

swiper.params

SwiperOptions

Object with the current effective initialization parameters. May differ from originalParams after responsive breakpoints kick in or after a parameter is changed at runtime.

swiper.previousIndex

number

Index number of the slide that was active before the current one.

swiper.progress

number

Current progress of the wrapper translate, as a value between 0 (at the first slide) and 1 (at the last slide).

swiper.realIndex

number

Index of the currently active slide in the original slide list. In loop mode this skips the cloned duplicate slides, while activeIndex counts them.

swiper.slides

HTMLElement[]

Array of slide HTML elements. To get a specific slide use swiper.slides[1] (the second slide), swiper.slides[0] (the first), etc.

swiper.slidesEl

HTMLElement

HTML element of the slide wrapper (the element with the swiper-wrapper CSS class). Same as swiper.wrapperEl.

swiper.slidesGrid

number[]

Array of slide start positions (in pixels) along the slider track.

swiper.slidesSizesGrid

number[]

Array of slide widths (or heights, for vertical sliders) in pixels.

swiper.snapGrid

number[]

Array of snap positions (in pixels). A snap position is where the slider comes to rest after a swipe.

swiper.snapIndex

number

Index of the current snap in snapGrid.

swiper.swipeDirection

'next' | 'prev'

Direction of the current/last swipe: 'next' or 'prev'.

swiper.touches

object

Object with current touch / pointer coordinates:

  • swiper.touches.startX  — X position where the touch started

  • swiper.touches.startY  — Y position where the touch started

  • swiper.touches.currentX — X position right now (during the move)

  • swiper.touches.currentY — Y position right now (during the move)

  • swiper.touches.diff  — distance dragged since startX / startY (positive or negative)

swiper.translate

number

Current value of the wrapper’s CSS translate (in pixels). Negative values move the wrapper to the left (or up).

swiper.width

number

Current width of the slider container (in pixels).

swiper.wrapperEl

HTMLElement

HTML element of the slide wrapper (same as swiper.slidesEl).

Methods

A method is a function you can call on the Swiper instance to make it do something at runtime — for example, jump to a specific slide, update its layout after you added new slides, or attach an event handler. You usually have to grab the instance first:

// 1. Initialise a slider:
const mySwiper = new Swiper('.my-swiper-container');
// 2. Call any method on it:
mySwiper.slideNext();         // go to the next slide
mySwiper.slideTo(3, 600);     // animate to slide index 3 in 600 ms

In J1 Template the instance is also stored on the slider’s container element as the swiper property, so you can write:

document.querySelector('#my-swiper').swiper.slideNext();

The table below lists all methods exposed by the core Swiper instance in alphabetical order. Module-specific methods (for example swiper.autoplay.start() or swiper.zoom.in()) are listed in the Modules section further down this page.

Name Description

swiper.attachEvents()

Re-attach all built-in event listeners on the slider container. Useful only after a previous detachEvents() call.

swiper.changeDirection(newDirection, needUpdate)

Switch the slider between horizontal and vertical layout.

  • newDirection — String, 'horizontal' or 'vertical'. If omitted, the slider flips to the opposite of its current direction.

  • needUpdate  — Boolean, default true. When true, update() is called automatically after the direction change.

swiper.changeLanguageDirection(direction)

Switch the slider between left-to-right and right-to-left reading direction.

  • direction — String, 'ltr' (left-to-right) or 'rtl' (right-to-left).

swiper.destroy(deleteInstance, cleanStyles)

Destroy the slider instance and remove all internal event listeners. Use this when you no longer need the slider, or before re-creating it with new options.

  • deleteInstance — Boolean, default true. Set to false to keep the Swiper object in memory (only the listeners are removed).

  • cleanStyles  — Boolean, default true. Set to true to remove all inline styles from the container, the wrapper and the slides. Helpful if you want to re-initialise the same DOM with different options or in a different direction.

swiper.detachEvents()

Detach all built-in event listeners without destroying the slider. Counterpart to attachEvents().

swiper.disable()

Disable the slider. While disabled, Swiper hides its navigation elements and ignores any touch, mouse or keyboard input.

swiper.enable()

Re-enable a previously disabled slider.

Swiper.extendDefaults(options)

Extend the global Swiper defaults so that every slider created after this call inherits the given options.

This is a static method on the Swiper class, not on a slider instance. Call it once before any new Swiper(…​) so the new defaults take effect.

swiper.getTranslate()

Return the current CSS translate value (in pixels) of the slide wrapper.

swiper.init(el)

Initialise the slider. Only needed when you created the instance with init: false.

  • el — HTMLElement, optional container element to mount the slider on. If omitted, the original container is used.

swiper.maxTranslate()

Return the maximum (most negative) translate value the wrapper can reach — the position of the last slide.

swiper.minTranslate()

Return the minimum translate value the wrapper can reach — the position of the first slide.

swiper.off(event, handler)

Remove a previously registered event handler.

  • event  — String. Name of the event (e.g. 'slideChange') or a space-separated list of names.

  • handler — Function. The exact same function reference you passed to on(). Without handler, all handlers for event are removed.

swiper.offAny(handler)

Remove a handler that was registered with onAny().

swiper.on(event, handler)

Register an event handler.

  • event  — String. Name of the event (e.g. 'slideChange') or a space-separated list of names.

  • handler — Function. Called every time the event fires.

mySwiper.on('slideChange', function () {
  console.log('Active slide is now:', this.activeIndex);
});

swiper.onAny(handler)

Register a handler that is called for every event fired by Swiper. Useful for debugging.

mySwiper.onAny(function (eventName, ...args) {
  console.log('Swiper event:', eventName, args);
});

swiper.once(event, handler)

Register an event handler that fires only once and is then automatically removed.

swiper.setGrabCursor()

Set the CSS grab cursor on the slider container. Normally you do not need to call this manually — enable the grabCursor parameter instead.

swiper.setProgress(progress, speed)

Move the slider to a specific progress position between 0 (first slide) and 1 (last slide).

  • progress — Number, 0 to 1.

  • speed  — Number, transition duration in milliseconds. Defaults to the slider’s speed parameter.

swiper.setTranslate(translate)

Set the CSS translate of the slide wrapper to an exact pixel value. Low-level method — prefer slideTo() or setProgress() when possible.

  • translate — Number, the new translate value in pixels.

swiper.slideNext(speed, runCallbacks)

Animate to the next slide.

  • speed  — Number, transition duration in milliseconds.

  • runCallbacks — Boolean, default true. Set false to skip the transition events for this call.

swiper.slidePrev(speed, runCallbacks)

Animate to the previous slide.

  • speed  — Number, transition duration in milliseconds.

  • runCallbacks — Boolean, default true. Set false to skip the transition events for this call.

swiper.slideReset(speed, runCallbacks)

Animate back to the currently active slide. Useful for cancelling a partial swipe.

  • speed  — Number, transition duration in milliseconds.

  • runCallbacks — Boolean, default true.

swiper.slideTo(index, speed, runCallbacks)

Animate to the slide with the given index.

  • index  — Number. Zero-based slide index (0 is the first slide).

  • speed  — Number, transition duration in milliseconds.

  • runCallbacks — Boolean, default true.

swiper.slideToClosest(speed, runCallbacks)

Snap the slider to the closest slide / snap position. Mostly useful in freeMode after a free drag.

  • speed  — Number, transition duration in milliseconds.

  • runCallbacks — Boolean, default true.

swiper.slideToLoop(index, speed, runCallbacks)

Same as slideTo() but for loop mode: takes the real slide index (without the cloned slides) and figures out the matching internal index for you.

  • index  — Number. Zero-based real slide index.

  • speed  — Number, transition duration in milliseconds.

  • runCallbacks — Boolean, default true.

swiper.slidesPerViewDynamic()

Return the number of slides visible right now. Useful only when slidesPerView: 'auto' is set, because in that case the visible count depends on slide widths and the container size.

swiper.translateTo(translate, speed, runCallbacks, translateBounds)

Animate the wrapper’s CSS translate to an exact pixel value.

  • translate  — Number, target translate value (in pixels).

  • speed  — Number, transition duration in milliseconds.

  • runCallbacks  — Boolean, default true. Set false to skip transition events.

  • translateBounds — Boolean, default true. Set false to allow the value to go beyond the normal minimum / maximum.

swiper.unsetGrabCursor()

Remove the CSS grab cursor from the slider container (counterpart of setGrabCursor()).

swiper.update()

Recalculate everything: sizes, slide grid, progress and slide classes. Call this after you have added or removed slides manually, shown or hidden the slider, or made any other DOM changes that affect the layout. Internally this calls the four updateXxx() methods below in the right order.

swiper.updateAutoHeight(speed)

Force Swiper to recalculate its height to match the active slide. Use this together with autoHeight: true.

  • speed — Number, transition duration in milliseconds.

swiper.updateProgress()

Recalculate the slider’s progress value.

swiper.updateSize()

Recalculate the size of the slider container.

swiper.updateSlides()

Recalculate the number of slides and their offsets. Call after adding or removing slides from JavaScript.

swiper.updateSlidesClasses()

Refresh the active, prev, next and visible CSS classes on slides and pagination bullets.

swiper.use(modules)

Install one or more Swiper modules at runtime.

  • modules — Array of Swiper module references.

import Swiper from 'swiper';
import { Navigation, Pagination } from 'swiper/modules';
Swiper.use([Navigation, Pagination]);

Events

Swiper comes with a bunch of useful events you can listen to. Events can be assigned in two ways:

  1. Using the on parameter on swiper initialisation:

const swiper = new Swiper('.swiper', {
  // ...
  on: {
    init: function () {
      console.log('swiper initialized');
    },
  },
});
  1. Using the on method after swiper initialisation:

const swiper = new Swiper('.swiper', {
  // ...
});
swiper.on('slideChange', function () {
  console.log('slide changed');
});

The this keyword inside an event handler always points to the Swiper instance.

The table below lists the core Swiper events that work for any slider. Modules add their own events on top (for example autoplayStart, navigationNext, paginationRender, scroll, keyPress, zoomChange, …​). Module-specific events are listed in the Modules section further down this page.

Name Arguments Description

activeIndexChange

(swiper)

Fired when the active slide index changes. In loop mode this counts the cloned slides; use realIndexChange if you need the index in the original slide list.

afterInit

(swiper)

Fired right after the slider has been initialised.

beforeDestroy

(swiper)

Fired right before the slider is destroyed.

beforeInit

(swiper)

Fired right before the slider is initialised.

beforeLoopFix

(swiper)

Fired right before Swiper rearranges the cloned slides in loop mode.

beforeResize

(swiper)

Fired before Swiper’s internal resize handler runs.

beforeSlideChangeStart

(swiper)

Fired right before the slide-change transition starts.

beforeTransitionStart

(swiper, speed, internal)

Fired before any transition starts. Receives the transition duration (in ms) and an internal flag.

breakpoint

(swiper, breakpointParams)

Fired when a responsive breakpoint becomes active. Receives the parameters that belong to that breakpoint.

changeDirection

(swiper)

Fired when the slider’s direction changes (see changeDirection() method).

click

(swiper, event)

Fired when the user clicks or taps the slider. Receives the underlying pointerup event as an argument.

destroy

(swiper)

Fired when the slider has been destroyed.

disable

(swiper)

Fired when the slider is disabled through swiper.disable() (or when watchOverflow decides there is nothing to slide). While disabled, Swiper hides its navigation elements and ignores all input.

doubleClick

(swiper, event)

Fired when the user double-clicks or double-taps the slider.

doubleTap

(swiper, event)

Fired when the user double-taps the slider container. Receives the underlying pointerup event as an argument.

enable

(swiper)

Fired when a previously disabled slider is re-enabled through swiper.enable(). Counterpart of the disable event.

fromEdge

(swiper)

Fired when the Swiper leaves the beginning or end position (i.e. moves away from the first or the last slide).

init

(swiper)

Fired right after Swiper initialization. Note that with swiper.on('init') syntax it will work only in case you set init: false parameter.

const swiper = new Swiper('.swiper', {
  init: false,
  // other parameters
});
swiper.on('init', function() {
 // do something
});
swiper.init();
const swiper = new Swiper('.swiper', {
  // other parameters
  on: {
    init: function () {
      // do something
    },
  }
});

lock

(swiper)

Fired when the slider is locked (only when watchOverflow is enabled and there are not enough slides to scroll).

loopFix

(swiper)

Fired after Swiper has rearranged the cloned slides in loop mode.

momentumBounce

(swiper)

Fired on the bounce-back at the end of a momentum drag in freeMode.

observerUpdate

(swiper)

Fired when the observer is enabled and detects DOM mutations in the slider.

orientationchange

(swiper)

Fired when the device orientation changes (e.g. landscape ↔ portrait).

progress

(swiper, progress)

Fired whenever the slider’s progress changes. Receives the progress as a number between 0 and 1.

reachBeginning

(swiper)

Fired when the slider reaches its beginning (the first slide).

reachEnd

(swiper)

Fired when the slider reaches its end (the last slide).

realIndexChange

(swiper)

Fired when the real index changes (i.e. the slide index in the original list, ignoring loop-mode clones).

resize

(swiper)

Fired on window resize, right before Swiper’s internal resize handling runs.

setTransition

(swiper, transition)

Fired every time the slider starts an animation. Receives the transition duration (in ms).

setTranslate

(swiper, translate)

Fired whenever the wrapper’s translate value changes. Receives the new translate value (in px).

slideChange

(swiper)

Fired when the currently active slide changes.

slideChangeTransitionEnd

(swiper)

Fired after the animation to another slide (next or previous) has ended.

slideChangeTransitionStart

(swiper)

Fired at the beginning of the animation to another slide (next or previous).

slideNextTransitionEnd

(swiper)

Same as slideChangeTransitionEnd but for the forward direction only.

slideNextTransitionStart

(swiper)

Same as slideChangeTransitionStart but for the forward direction only.

slidePrevTransitionEnd

(swiper)

Same as slideChangeTransitionEnd but for the backward direction only.

slidePrevTransitionStart

(swiper)

Same as slideChangeTransitionStart but for the backward direction only.

slideResetTransitionEnd

(swiper)

Fired at the end of the animation that resets the slider to the current slide.

slideResetTransitionStart

(swiper)

Fired at the beginning of the animation that resets the slider to the current slide.

sliderFirstMove

(swiper, event)

Fired on the very first touch/drag move of a swipe gesture.

sliderMove

(swiper, event)

Fired while the user is dragging the slider with a finger or the mouse. Receives the underlying pointermove event.

slidesGridLengthChange

(swiper)

Fired when the slides grid (array of slide positions) changes.

slidesLengthChange

(swiper)

Fired when the number of slides changes.

slidesUpdated

(swiper)

Fired after slides and their sizes have been (re)calculated.

snapGridLengthChange

(swiper)

Fired when the snap grid (array of snap positions) changes.

snapIndexChange

(swiper)

Fired when the snap index changes.

tap

(swiper, event)

Fired when the user taps or clicks the slider. Receives the underlying pointerup event as an argument.

toEdge

(swiper)

Fired when the slider reaches the beginning or end position.

touchEnd

(swiper, event)

Fired when the user releases the slider. Receives the underlying pointerup event as an argument.

touchMove

(swiper, event)

Fired while the user is moving a finger over the slider. Receives the underlying pointermove event as an argument.

touchMoveOpposite

(swiper, event)

Fired while the user is moving a finger over the slider in the opposite direction of the slider’s direction parameter (e.g. swiping vertically on a horizontal slider). Receives the underlying pointermove event as an argument.

touchStart

(swiper, event)

Fired when the user first touches the slider. Receives the underlying pointerdown event as an argument.

transitionEnd

(swiper)

Fired after any transition.

transitionStart

(swiper)

Fired at the beginning of any transition.

unlock

(swiper)

Fired when the slider becomes unlocked (only when watchOverflow is enabled).

update

(swiper)

Fired after a swiper.update() call.

Modules

Swiper is built from a core and a set of optional modules. Each module adds a single feature (navigation arrows, pagination dots, autoplay, zoom and so on) and can be turned on or off independently. The J1 bundle (swiper-bundle.js) ships with all of the modules listed below pre-registered, so you only need to enable them in the Swiper parameters — no extra import is required.

Most modules follow the same pattern. A module is enabled by adding its name to the Swiper options, either as boolean true (use the default settings) or as an object (override one or more options):

const swiper = new Swiper('.swiper', {
  // shortest form -- use module defaults
  navigation: true,
  // expanded form -- pass custom options
  pagination: {
    el: '.swiper-pagination',
    clickable: true,
  },
});

Once Swiper is created, modules expose three optional building blocks:

  • Properties — read-only values you can inspect on the instance (for example swiper.navigation.nextEl).

  • Methods — helper functions you can call from your own code (for example swiper.autoplay.stop()).

  • Events — callbacks Swiper fires when something changes (registered with swiper.on('eventName', handler)).

A11y (Accessibility)

Accessibility makes the slider usable by assistive technologies such as screen readers and by visitors who navigate only with the keyboard. The term a11y is the common abbreviation for accessibility (11 letters between the a and the y).

Parameters

Once the Accessibility module is activated, Swiper automatically adds ARIA attributes and semantic roles to the DOM. Specifically, important ARIA attributes such as aria-live, aria-label, and role are automatically added to the slider and its controls so that screen reader users can understand the purpose of the slider and navigate between the slides.

Additionally, the module adds role="region" and an aria-label to the carousel container, eliminating the need to set these ARIA attributes manually.

Object with a11y parameters or boolean true to enable with default settings.

const swiper = new Swiper('.swiper', {
  a11y: {
    prevSlideMessage: 'Previous slide',
    nextSlideMessage: 'Next slide',
  },
});
Name Type Default Description

containerMessage

string | null

null

Message for screen readers for outer swiper container

containerRole

string | null

null

Value of the "role" attribute to be set on the swiper container

containerRoleDescriptionMessage

string | null

null

Message for screen readers describing the role of outer swiper container.

enabled

boolean

true

Enables A11y

firstSlideMessage

string

'This is the first slide'

Message for screen readers for previous button when swiper is on first slide.

id

string | number | null

null

Value of id attribute to be set on swiper-wrapper. If null will be generated automatically.

itemRoleDescriptionMessage

string | null

null

Message for screen readers describing the role of slide element.

lastSlideMessage

string

'This is the last slide'

Message for screen readers for next button when swiper is on last slide.

nextSlideMessage

string

'Next slide'

Message for screen readers for next button.

notificationClass

string

'swiper-notification'

CSS class name of a11y notification.

paginationBulletMessage

string

'Go to slide \{{index}}'

Message for screen readers for single pagination bullet.

prevSlideMessage

string

'Previous slide'

Message for screen readers for previous button.

scrollOnFocus

boolean

true

Enables scrolling to the slide that has been focused.

slideLabelMessage

string

'\{{index}} / \{{slidesLength}}'

Message for screen readers describing the label of slide element.

slideRole

string

'group'

Value of swiper slide role attribute.

Autoplay

Makes the slider advance to the next slide automatically after a configurable delay. By default autoplay stops once the visitor swipes or clicks a navigation button; set disableOnInteraction: false to keep it running.

Parameters

The table below lists the options that go inside the autoplay object. Pass autoplay: true to enable the module with the default settings (3 seconds delay, autoplay stops after the first user interaction).

Object with autoplay parameters or boolean true to enable with default settings

const swiper = new Swiper('.swiper', {
 autoplay: {
   delay: 5000,
 },
});
Name Type Default Description

delay

number

3000

Delay between transitions (in ms). If this parameter is not specified, auto play will be disabled.

If you need to specify different delay for specific slides you can do it by using data-swiper-autoplay (in ms) attribute on slide.

<!-- hold this slide for 2 seconds -->
<div class="swiper-slide" data-swiper-autoplay="2000">

disableOnInteraction

boolean

false

If set to true autoplay will be permanently stopped after the first user interaction (swipe, navigation click, …​). With the default of false autoplay simply pauses during the interaction and restarts afterwards.

enabled

boolean

false

Whether autoplay is enabled. Set automatically to true when you pass autoplay: true or an autoplay object.

pauseOnMouseEnter

boolean

false

When enabled autoplay will be paused on pointer (mouse) enter over Swiper container.

reverseDirection

boolean

false

Enables autoplay in reverse direction

stopOnLastSlide

boolean

false

Enable this parameter and autoplay will be stopped when it reaches last slide (has no effect in loop mode)

waitForTransition

boolean

true

When enabled autoplay will wait for wrapper transition to continue. Can be disabled in case of using Virtual Translate when your slider may not have transition

Properties

After the slider is created, the current autoplay state is available on swiper.autoplay:

Name Type Description

swiper.autoplay.paused

boolean

Whether autoplay is paused

swiper.autoplay.running

boolean

Whether autoplay enabled and running

swiper.autoplay.timeLeft

number

If autoplay is paused, it contains time left (in ms) before transition to next slide

Methods

The autoplay module exposes simple helper methods on the slider instance. Use them to start, stop, pause or resume autoplay from your own code (for example from a custom play/pause button).

Name Description

swiper.autoplay.pause()

Pause autoplay

swiper.autoplay.resume()

Resume autoplay

swiper.autoplay.start()

Start autoplay

swiper.autoplay.stop()

Stop autoplay

Events

When the autoplay module is active, Swiper fires the following extra events. Register them with swiper.on('eventName', handler) like any other Swiper event.

Name Arguments Description

autoplay

(swiper)

Event is fired when slide changed with autoplay

autoplayPause

(swiper)

Event is fired on autoplay pause

autoplayResume

(swiper)

Event is fired on autoplay resume

autoplayStart

(swiper)

Event is fired in when autoplay started

autoplayStop

(swiper)

Event is fired when autoplay stopped

autoplayTimeLeft

(swiper, timeLeft, percentage)

Event triggers continuously while autoplay is enabled. It contains time left (in ms) before transition to next slide and percentage of that time related to autoplay delay

Cards Effect

Stacks the slides like a deck of playing cards: the active slide sits on top and the others appear slightly offset and rotated behind it. To activate the effect set the global Swiper option effect: 'cards' and tune the offsets and rotation with the cardsEffect object below.

Parameters

The table below lists the options that go inside the cardsEffect object. They control how much each card behind the active one is offset and rotated, and whether to draw shadows between them.

Object with Cards-effect parameters

const swiper = new Swiper('.swiper', {
  effect: 'cards',
  cardsEffect: {
    // ...
  },
});
Name Type Default Description

perSlideOffset

number

8

Offset distance per slide (in px)

perSlideRotate

number

2

Rotate angle per slide (in degrees)

rotate

boolean

true

Enables cards rotation

slideShadows

boolean

true

Enables slides shadows

Controller

The Controller module links two (or more) Swiper instances together so they slide in sync. It is the most generic way to make sliders follow each other; if you only need a thumbnail strip have a look at the more specialised Thumbs module instead.

Parameters

The table below lists the options that go inside the controller object. The required option is control, which must reference another Swiper instance (or an array of them).

Object with controller parameters or boolean true to enable with default settings

const swiper = new Swiper('.swiper', {
  controller: {
    inverse: true,
  },
});
Name Type Default Description

by

'slide' | 'container'

'slide'

Defines a way how to control another slider: slide by slide (with respect to other slider’s grid) or depending on all slides/container (depending on total slider percentage).

control

string | Swiper | Swiper[] | HTMLElement | null

none

Pass here another Swiper instance or array with Swiper instances that should be controlled by this Swiper. Also accepts string with CSS selector of Swiper element, or HTMLElement of Swiper element

inverse

boolean

false

Set to true and controlling will be in inverse direction

Properties

After the slider is created, the linked controlled Swiper instance(s) are available on swiper.controller:

Name Type Description

swiper.controller.control

Swiper | Swiper[]

Pass here another Swiper instance or array with Swiper instances that should be controlled by this Swiper

Coverflow Effect

Coverflow makes the slides look like covers in a 3-D shelf: the active slide is in front and the others rotate and recede into the background. To activate the effect set the global Swiper option effect: 'coverflow' and fine-tune the look with the coverflowEffect object below.

Parameters

The table below lists the options that go inside the coverflowEffect object. They control the rotation angle, the depth offset and other 3-D parameters of the coverflow look.

Object with Coverflow-effect parameters.

const swiper = new Swiper('.swiper', {
  effect: 'coverflow',
  coverflowEffect: {
    rotate: 30,
    slideShadows: false,
  },
});
Name Type Default Description

depth

number

100

Depth offset in px (slides translate in Z axis)

modifier

number

1

Effect multiplier

rotate

number

50

Slide rotate in degrees

scale

number

1

Slide scale effect

slideShadows

boolean

true

Enables slides shadows

stretch

number | string

0

Stretch space between slides

  • a number is interpreted as pixels (e.g., 20 for 20px).

  • a string with a percentage (e.g., "50%").

Creative Effect

The most flexible of the built-in effects: lets you describe arbitrary next and prev transforms (translate, rotate, scale, opacity) for the slides around the active one. To activate the effect set the global Swiper option effect: 'creative' and configure the transforms in the creativeEffect object below.

Parameters

The table below lists the options that go inside the creativeEffect object. The most important options are prev and next, which each accept a transform object (see the second source block below for the full shape).

Object with Creative-effect parameters

const swiper = new Swiper('.swiper', {
  effect: 'creative',
  creativeEffect: {
    prev: {
      // will set `translateZ(-400px)` on previous slides
      translate: [0, 0, -400],
    },
    next: {
      // will set `translateX(100%)` on next slides
      translate: ['100%', 0, 0],
    },
  },
});
{
  // Array with translate X, Y and Z values
  translate: (string | number)[];
  // Array with rotate X, Y and Z values (in deg)
  rotate?: number[];
  // Slide opacity
  opacity?: number;
  // Slide scale
  scale?: number;
  // Enables slide shadow
  shadow?: boolean;
  // Transform origin, e.g. `left bottom`
  origin?: string;
}
Name Type Default Description

limitProgress

number

1

Limit progress/offset to amount of side slides. If 1, then slides all slides after prev/next will have same state. If 2, then all slides after 2nd before/after active will have same state, etc.

next

CreativeEffectTransform

none

Next slide transformations.

perspective

boolean

true

Enable this parameter if your custom transforms require 3D transformations (translateZ, rotateX, rotateY )

prev

CreativeEffectTransform

none

Previous slide transformations. Accepts object of the following type:

progressMultiplier

number

1

Allows to multiply slides transformations and opacity.

shadowPerProgress

boolean

false

Splits shadow "opacity" per slide based on limitProgress (only if transformation shadows enabled). E.g. setting limitProgress: 2 and enabling shadowPerProgress, will set shadow opacity to 0.5 and 1 on two slides next to active. With this parameter disabled, all slides beside active will have shadow with 1 opacity

Cube Effect

Arranges the slides on the four sides of a rotating cube. As the visitor swipes, the cube rotates so the next side comes into view. To activate the effect set the global Swiper option effect: 'cube' and tune the look with the cubeEffect object below.

Parameters

The table below lists the options that go inside the cubeEffect object. They control the drop shadow under the cube and the small shadows on the slide faces.

Object with Cube-effect parameters

const swiper = new Swiper('.swiper', {
  effect: 'cube',
  cubeEffect: {
    slideShadows: false,
  },
});
Name Type Default Description

shadow

boolean

true

Enables main slider shadow

shadowOffset

number

20

Main shadow offset in px

shadowScale

number

0.94

Main shadow scale ratio

slideShadows

boolean

true

Enables slides shadows

Fade Effect

Replaces the default horizontal "slide" transition with a fade between slides. To activate the effect set the global Swiper option effect: 'fade' and (optionally) fine-tune it with the fadeEffect object described below.

crossFade should be set to true in order to avoid seeing content behind or underneath.

Parameters

The fadeEffect object has a single option, crossFade, which controls whether the outgoing slide fades out at the same time the incoming slide fades in. Leave it disabled if your slides have a solid background, enable it whenever slides may be transparent.

Object with Fade-effect parameters

const swiper = new Swiper('.swiper', {
  effect: 'fade',
  fadeEffect: {
    crossFade: true
  },
});
Name Type Default Description

crossFade

boolean

false

Enables slides cross fade

Flip Effect

Replaces the default "slide" transition with a flip: the active slide rotates out of view while the next one rotates in, like turning a card. To activate the effect set the global Swiper option effect: 'flip' and (optionally) tune it with the flipEffect object below.

Parameters

The flipEffect object has two switches: one to keep the rotation limited to slides next to the active one, and one to add a slight shadow during the flip.

Object with Flip-effect parameters

const swiper = new Swiper('.swiper', {
  effect: 'flip',
  flipEffect: {
    slideShadows: false,
  },
});
Name Type Default Description

limitRotation

boolean

true

Limit edge slides rotation

slideShadows

boolean

true

Enables slides shadows

Free Mode

Free mode turns the slider into a free-scrolling area: instead of snapping to a single slide on release, the visitor can flick through the slides and the wrapper keeps moving with momentum. Useful for slides that act more like a horizontally scrollable list.

Parameters

The table below lists the options that go inside the freeMode object. Pass freeMode: true to enable the module with the default settings, or pass an object to fine-tune momentum, snapping and sensitivity.

Enables free mode functionality. Object with free mode parameters or boolean true to enable with default settings.

const swiper = new Swiper('.swiper', {
  freeMode: true,
});
const swiper = new Swiper('.swiper', {
  freeMode: {
    enabled: true,
    sticky: true,
  },
});
Name Type Default Description

enabled

boolean

false

Whether the free mode is enabled

minimumVelocity

number

0.02

Minimum touchmove-velocity required to trigger free mode momentum

momentum

boolean

true

If enabled, then slide will keep moving for a while after you release it

momentumBounce

boolean

true

Set to false if you want to disable momentum bounce in free mode

momentumBounceRatio

number

1

Higher value produces larger momentum bounce effect

momentumRatio

number

1

Higher value produces larger momentum distance after you release slider

momentumVelocityRatio

number

1

Higher value produces larger momentum velocity after you release slider

sticky

boolean

false

Set to enabled to enable snap to slides positions in free mode

Grid

The Grid module turns the single-row slider into a multi-row grid: each "page" of the slider can show several rows of slides at once. Useful for image grids, product tiles or any layout where you want to show more than one slide vertically.

Parameters

The table below lists the options that go inside the grid object. Unlike most other modules the Grid module does not accept boolean true — you must pass an object with at least the rows parameter set to a value greater than 1.

Object with grid parameters to enable "multirow" slider.

const swiper = new Swiper('.swiper', {
  grid: {
    rows: 2,
  },
});
Name Type Default Description

fill

'row' | 'column'

'column'

Can be column or row. Defines how slides should fill rows, by column or by row

if used with loop mode make sure number of slides is even specified in loop mode requirements, or enable loopAddBlankSlides parameter

rows

number

1

Number of slides rows, for multirow layout

Hash Navigation

Hash navigation is intended to have a link to specific slide that allows to load page with specific slide opened.

To make it work, you need to enable it by passing hashNavigation:true parameter and adding slides hashes in data-hash attribute:

<div class="swiper">
  <div class="swiper-wrapper">
    <div class="swiper-slide" data-hash="slide1">Slide 1</div>
    <div class="swiper-slide" data-hash="slide2">Slide 2</div>
    <div class="swiper-slide" data-hash="slide3">Slide 3</div>
    <div class="swiper-slide" data-hash="slide4">Slide 4</div>
    <div class="swiper-slide" data-hash="slide5">Slide 5</div>
    ...
  </div>
</div>
const swiper = new Swiper('.swiper', {
  //enable hash navigation
  hashNavigation: true,
});

Parameters

The table below lists the options that go inside the hashNavigation object. Pass hashNavigation: true to enable the module with the default settings (the URL hash is added to the browser history each time the active slide changes).

Enables hash url navigation to for slides. Object with hash navigation parameters or boolean true to enable with default settings

const swiper = new Swiper('.swiper', {
  hashNavigation: {
    replaceState: true,
  },
});
Name Type Default Description

enabled

boolean

false

Whether hash navigation is enabled.

getSlideIndex

function(Swiper, string)

none

Designed to be used with Virtual slides when it is impossible to find slide in DOM by hash (e.g. not yet rendered)

replaceState

boolean

false

Works in addition to hashnav to replace current url state with the new one instead of adding it to history

watchState

boolean

false

Set to true to enable also navigation through slides (when hashnav is enabled) by browser history or by setting directly hash on document location

Events

When the hash navigation module is active, Swiper fires the following extra events whenever the URL hash changes (either by the browser or by Swiper itself).

Name Arguments Description

hashChange

(swiper)

Event is fired on window hash change

hashSet

(swiper)

Event is fired when swiper updates the hash

History Navigation

History Navigation makes every slide a real URL using the browser’s history.pushState API. The visitor can bookmark a slide, share its URL or use the browser’s Back / Forward buttons to walk through the slides. Unlike Hash Navigation it changes the path, not just the #hash.

Parameters

The table below lists the options that go inside the history object. The typical setup is to pick a URL key (e.g. "slides") and to give each slide a data-history attribute with the URL part to use for that slide.

Enables history push state where every slide will have its own url. In this parameter you have to specify main slides url like "slides" and specify every slide url using data-history attribute.

Object with history navigation parameters or boolean true to enable with default settings

const swiper = new Swiper('.swiper', {
  history: {
    replaceState: true,
  },
});
<!-- will produce "slides/slide1" url in browser history -->
<div class="swiper-slide" data-history="slide1"></div>
Name Type Default Description

enabled

boolean

false

Enables History Plugin.

keepQuery

boolean

false

Keep query parameters when changing browser url.

key

string

'slides'

Url key for slides

replaceState

boolean

false

Works in addition to hashnav or history to replace current url state with the new one instead of adding it to history.

root

string

''

Swiper page root, useful to specify when you use Swiper history mode not on root website page. For example can be https://my-website.com/ or https://my-website.com/subpage/ or /subpage/

Keyboard Control

Lets visitors navigate the slider with the keyboard arrow keys (and optionally with Page Up / Page Down). Useful for accessibility and for desktop users who prefer the keyboard over the mouse.

Parameters

The table below lists the options that go inside the keyboard object. Pass keyboard: true to enable the module with the default settings (left/right arrows move the slider, only when it is in the viewport).

Enables navigation through slides using keyboard. Object with keyboard parameters or boolean true to enable with default settings

const swiper = new Swiper('.swiper', {
  keyboard: {
    enabled: true,
    onlyInViewport: false,
  },
});
Name Type Default Description

enabled

boolean

false

Set to true to enable keyboard control

onlyInViewport

boolean

true

When enabled it will control sliders that are currently in viewport

pageUpDown

boolean

true

When enabled it will enable keyboard navigation by Page Up and Page Down keys

Properties

After the slider is created, the current keyboard state is available on swiper.keyboard:

Name Type Description

swiper.keyboard.enabled

boolean

Whether the keyboard control is enabled

Methods

The keyboard module exposes two helper methods to turn keyboard control on or off from your own code at runtime.

Name Description

swiper.keyboard.disable()

Disable keyboard control

swiper.keyboard.enable()

Enable keyboard control

Events

When the keyboard module is active, Swiper fires the following extra event whenever the visitor presses a key that the module handles.

Name Arguments Description

keyPress

(swiper, keyCode)

Event is fired on key press

Lazy Loading

Since version 9 Swiper doesn’t have a specific lazy loading API, as it relies on native browser lazy loading feature. To use lazy loading, we just need to set loading="lazy" on images and add preloader element:

<div class="swiper">
  <div class="swiper-wrapper">
    <!-- Lazy image -->
    <div class="swiper-slide">
      <img src="path/to/picture-1.jpg" loading="lazy" />
      <div class="swiper-lazy-preloader"></div>
    </div>
    <!-- Lazy image with srcset -->
    <div class="swiper-slide">
      <img
        src="path/to/logo-small.png"
        srcset="path/to/logo-large.png 2x"
        loading="lazy"
      />
      <div class="swiper-lazy-preloader"></div>
    </div>
  </div>
</div>

As you see:

  • Lazy image must have loading="lazy" attribute

  • Add animated preloader spinner to slide which will be removed automatically after image loaded:

<div class="swiper-lazy-preloader"></div>

Or white one for dark layout:

<div class="swiper-lazy-preloader swiper-lazy-preloader-white"></div>

Manipulation

The Manipulation module adds helper methods that let you add, remove and replace slides from your own JavaScript after the slider has been created. It is intended to be used only with the Swiper Core version; if you build your slides with React or Vue you should add or remove items from the framework state instead.

Methods

The methods below are added directly to the swiper instance (not to a sub-namespace). They accept either an HTML string, an HTMLElement or an array of either, so you can build new slides in code and insert them dynamically.

Name Description

swiper.addSlide(index, slides)

Add new slides to the required index. slides could be HTMLElement or HTML string with new slide or array with such slides, for example:

swiper.addSlide(1, '<div class="swiper-slide">Slide 10"</div>')
swiper.addSlide(1, [
 '<div class="swiper-slide">Slide 10"</div>',
 '<div class="swiper-slide">Slide 11"</div>'
]);

swiper.appendSlide(slides)

Add new slides to the end. slides could be HTMLElement or HTML string with new slide or array with such slides, for example:

swiper.appendSlide('<div class="swiper-slide">Slide 10"</div>')
swiper.appendSlide([
 '<div class="swiper-slide">Slide 10"</div>',
 '<div class="swiper-slide">Slide 11"</div>'
]);

swiper.prependSlide(slides)

Add new slides to the beginning. slides could be HTMLElement or HTML string with new slide or array with such slides, for example:

swiper.prependSlide('<div class="swiper-slide">Slide 0"</div>')
swiper.prependSlide([
 '<div class="swiper-slide">Slide 1"</div>',
 '<div class="swiper-slide">Slide 2"</div>'
]);

swiper.removeAllSlides()

Remove all slides

swiper.removeSlide(slideIndex)

Remove selected slides. slideIndex could be a number with slide index to remove or array with indexes.

swiper.removeSlide(0);       // remove first slide
swiper.removeSlide([0, 1]);  // remove first and second slides
swiper.removeAllSlides();    // Remove all slides

Mousewheel Control

Lets visitors navigate the slider with the mouse wheel (or with the two-finger swipe gesture on a trackpad). Useful for full-page sliders, image galleries and any layout where wheel scrolling should move between slides instead of scrolling the page.

Parameters

The table below lists the options that go inside the mousewheel object. Pass mousewheel: true to enable the module with the default settings.

Enables navigation through slides using mouse wheel. Object with mousewheel parameters or boolean true to enable with default settings

const swiper = new Swiper('.swiper', {
  mousewheel: {
    invert: true,
  },
});
Name Type Default Description

enabled

boolean

false

Set to true to enable mousewheel control

eventsTarget

HTMLElement | 'container' | 'wrapper' | CSSSelector

'container'

String with CSS selector or HTML element of the container accepting mousewheel events. By default it is swiper

forceToAxis

boolean

false

Set to true to force mousewheel swipes to axis. So in horizontal mode mousewheel will work only with horizontal mousewheel scrolling, and only with vertical scrolling in vertical mode.

invert

boolean

false

Set to true to invert sliding direction

noMousewheelClass

string

'swiper-no-mousewheel'

Scrolling on elements with this class will be ignored

releaseOnEdges

boolean

false

Set to true and swiper will release mousewheel event and allow page scrolling when swiper is on edge positions (in the beginning or in the end)

sensitivity

number

1

Multiplier of mousewheel data, allows to tweak mouse wheel sensitivity

thresholdDelta

number | null

null

Minimum mousewheel scroll delta to trigger swiper slide change

thresholdTime

number | null

null

Minimum mousewheel scroll time delta (in ms) to trigger swiper slide change

Properties

After the slider is created, the current mousewheel state is available on swiper.mousewheel:

Name Type Description

swiper.mousewheel.enabled

boolean

Whether the mousewheel control is enabled

Methods

The mousewheel module exposes two helper methods to turn mousewheel control on or off from your own code at runtime.

Name Description

swiper.mousewheel.disable()

Disable mousewheel control

swiper.mousewheel.enable()

Enable mousewheel control

Events

When the mousewheel module is active, Swiper fires the following extra event whenever a wheel event is handled by the slider.

Name Arguments Description

scroll

(swiper, event)

Event is fired on mousewheel scroll

Navigation

Adds two navigation buttons ("previous" and "next") next to the slider. Visitors click them to jump one slide back or forward. You can style the buttons with CSS or replace them with your own elements.

Name Type Description

navigation

boolean | NavigationOptions

Object with navigation parameters or boolean true to enable with default settings.

const swiper = new Swiper('.swiper', {
  navigation: {
    nextEl: '.swiper-button-next',
    prevEl: '.swiper-button-prev',
  },
});

Parameters

The table below lists the options that go inside the navigation object. You can also pass navigation: true instead of an object to turn navigation buttons on with the default settings (Swiper will then look for elements with the classes .swiper-button-prev and .swiper-button-next inside the slider container).

Name Type Default Description

disabledClass

string

'swiper-button-disabled'

CSS class name added to the navigation button when it becomes disabled (e.g. on the first or last slide if loop is off).

enabled

boolean

true

Whether the module is active. Mainly used together with breakpoints to enable or disable navigation at specific screen sizes.

hiddenClass

string

'swiper-button-hidden'

CSS class name added to the navigation button when it is hidden.

hideOnClick

boolean

false

If true, the navigation buttons are toggled (hidden / shown) when the visitor clicks on the slider container.

lockClass

string

'swiper-button-lock'

CSS class name added to the navigation button when it is locked (e.g. when watchOverflow is enabled and there are not enough slides to scroll).

navigationDisabledClass

string

'swiper-navigation-disabled'

CSS class name added to the swiper container when navigation is disabled by a breakpoint.

nextEl

HTMLElement | CSSSelector | null

null

CSS selector string or HTML element of the element that should act as the "next" button.

prevEl

HTMLElement | CSSSelector | null

null

CSS selector string or HTML element of the element that should act as the "previous" button.

Properties

After the slider is created, the resolved navigation buttons are available on swiper.navigation:

Name Type Description

swiper.navigation.nextEl

HTMLElement

HTMLElement of "next" navigation button

swiper.navigation.prevEl

HTMLElement

HTMLElement of "previous" navigation button

Methods

The navigation module adds a few helper methods to the slider instance. You usually do not need to call them by hand — Swiper takes care of initialising and updating the buttons — but they are useful if you build a custom navigation UI.

Name Description

swiper.navigation.destroy()

Destroy navigation

swiper.navigation.init()

Initialize navigation

swiper.navigation.update()

Update navigation buttons state (enabled/disabled)

Events

When the navigation module is active, Swiper fires the following extra events. They are registered with swiper.on('eventName', handler) like any other Swiper event (see the Events section above).

Name Arguments Description

navigationHide

(swiper)

Event is fired on navigation hide

navigationNext

(swiper)

Event is fired on navigation next button click

navigationPrev

(swiper)

Event is fired on navigation prev button click

navigationShow

(swiper)

Event is fired on navigation show

CSS

The look of the navigation buttons can be tuned through a small set of CSS custom properties (CSS variables). Set them on the slider container or on :root to change the size, position and colour of the arrows — no JavaScript needed.

{
  --swiper-navigation-size: 44px;
  --swiper-navigation-top-offset: 50%;
  --swiper-navigation-sides-offset: 10px;
  --swiper-navigation-color: var(--swiper-theme-color);
}

Pagination

Shows pagination indicators below (or beside) the slider so visitors can see how many slides exist and which one is active. Four built-in styles are available:

  • bullets  — a row of small dots (default)

  • fraction  — a "3 / 10" text counter

  • progressbar — a thin horizontal progress bar

  • custom  — render anything you want via the renderCustom function

Parameters

The table below lists the options that go inside the pagination object. You can also pass pagination: true instead of an object to turn pagination on with the default settings (Swiper will then look for an element with the class .swiper-pagination inside the slider container).

Object with pagination parameters or boolean true to enable with default settings.

const swiper = new Swiper('.swiper', {
  pagination: {
    el: '.swiper-pagination',
    type: 'bullets',
  },
});
Name Type Default Description

bulletActiveClass

string

'swiper-pagination-bullet-active'

CSS class name of currently active pagination bullet

bulletClass

string

'swiper-pagination-bullet'

CSS class name of single pagination bullet

bulletElement

string

'span'

Defines which HTML tag will be used to represent a single pagination bullet. Only for bullets pagination type.

clickable

boolean

false

If true then clicking on a pagination bullet will cause transition to the matching slide. Only for bullets pagination type.

clickableClass

string

'swiper-pagination-clickable'

CSS class name set to pagination when it is clickable

currentClass

string

'swiper-pagination-current'

CSS class name of the element with currently active index in "fraction" pagination

dynamicBullets

boolean

false

Good to enable if you use bullets pagination with a lot of slides. So it will keep only few bullets visible at the same time.

dynamicMainBullets

number

1

The number of main bullets visible when dynamicBullets enabled.

el

HTMLElement | CSSSelector | null

null

String with CSS selector or HTML element of the container with pagination

enabled

boolean

true

Whether the module is active. Mainly used together with breakpoints to enable or disable pagination at specific screen sizes.

formatFractionCurrent

function(number)

none

format fraction pagination current number. Function receives current number, and you need to return formatted value

formatFractionTotal

function(number)

none

format fraction pagination total number. Function receives total number, and you need to return formatted value

hiddenClass

string

'swiper-pagination-hidden'

CSS class name of pagination when it becomes inactive

hideOnClick

boolean

false

Toggle (hide/show) pagination container visibility after click on Slider’s container

horizontalClass

string

'swiper-pagination-horizontal'

CSS class name set to pagination in horizontal Swiper

lockClass

string

'swiper-pagination-lock'

CSS class name set to pagination when it is disabled

modifierClass

string

'swiper-pagination-'

The beginning of the modifier CSS class name that will be added to pagination depending on parameters

paginationDisabledClass

string

'swiper-pagination-disabled'

CSS class name added on swiper container and pagination element when pagination is disabled by breakpoint

progressbarFillClass

string

'swiper-pagination-progressbar-fill'

CSS class name of pagination progressbar fill element

progressbarOpposite

boolean

false

Makes pagination progressbar opposite to Swiper’s direction parameter, means vertical progressbar for horizontal swiper direction and horizontal progressbar for vertical swiper direction

progressbarOppositeClass

string

'swiper-pagination-progressbar-opposite'

CSS class name of pagination progressbar opposite

renderBullet

function(number, string)

null

This parameter allows totally customize pagination bullets, you need to pass here a function that accepts index number of pagination bullet and required element class name (className). Only for bullets pagination type

const swiper = new Swiper('.swiper', {
  //...
  pagination: {
    //...
    renderBullet: function (index, className) {
      return '<span class="' + className + '">' + (index + 1) + '</span>';
    },
  },
});

renderCustom

function(Swiper, number, number)

null

This parameter is required for custom pagination type where you have to specify how it should be rendered.

const swiper = new Swiper('.swiper', {
  //...
  pagination: {
    //...
    renderCustom: function (swiper, current, total) {
      return current + ' of ' + total;
    },
  },
});

renderFraction

function(string, string)

null

This parameter allows to customize "fraction" pagination html. Only for fraction pagination type

const swiper = new Swiper('.swiper', {
  //...
  pagination: {
    //...
    renderFraction: function (currentClass, totalClass) {
      return '<span class="' + currentClass + '"></span>' +
              ' of ' +
              '<span class="' + totalClass + '"></span>';
    },
  },
});

renderProgressbar

function(string)

null

This parameter allows to customize "progress" pagination. Only for progress pagination type

const swiper = new Swiper('.swiper', {
  //...
  pagination: {
    //...
    renderProgressbar: function (progressbarFillClass) {
      return '<span class="' + progressbarFillClass + '"></span>';
    },
  },
});

totalClass

string

'swiper-pagination-total'

CSS class name of the element with total number of "snaps" in "fraction" pagination

type

'bullets' | 'fraction' | 'progressbar' | 'custom'

'bullets'

String with type of pagination. Can be bullets, fraction, progressbar or custom

verticalClass

string

'swiper-pagination-vertical'

CSS class name set to pagination in vertical Swiper

Properties

After the slider is created, the resolved pagination element and its bullets are available on swiper.pagination:

Name Type Description

swiper.pagination.bullets

HTMLElement[]

Array of pagination bullet HTML elements. Only populated when type: 'bullets' is used. To get a specific bullet element use, for example, swiper.pagination.bullets[1] for the second bullet.

swiper.pagination.el

HTMLElement

The HTML element of the pagination container (the element matched by the el option).

Methods

The pagination module adds a few helper methods to the slider instance. You usually do not need to call them by hand — Swiper renders and updates the pagination automatically — but they are useful if you re-render slides outside of Swiper.

Name Description

swiper.pagination.destroy()

Destroy pagination

swiper.pagination.init()

Initialize pagination

swiper.pagination.render()

Render pagination layout

swiper.pagination.update()

Update pagination state (enabled/disabled/active)

Events

When the pagination module is active, Swiper fires the following extra events. They are registered with swiper.on('eventName', handler) like any other Swiper event (see the Events section above).

Name Arguments Description

paginationHide

(swiper)

Event is fired on pagination hide

paginationRender

(swiper, paginationEl)

Event is fired after pagination rendered

paginationShow

(swiper)

Event is fired on pagination show

paginationUpdate

(swiper, paginationEl)

Event is fired when pagination updated

CSS

The look of the pagination (bullet size and colour, position relative to the slider, progress-bar height, etc.) can be tuned through a set of CSS custom properties (CSS variables). Set them on the slider container or on :root to adjust the appearance — no JavaScript needed.

{
  --swiper-pagination-color: var(--swiper-theme-color);
  --swiper-pagination-left: auto;
  --swiper-pagination-right: 8px;
  --swiper-pagination-bottom: 8px;
  --swiper-pagination-top: auto;
  --swiper-pagination-fraction-color: inherit;
  --swiper-pagination-progressbar-bg-color: rgba(0, 0, 0, 0.25);
  --swiper-pagination-progressbar-size: 4px;
  --swiper-pagination-bullet-size: 8px;
  --swiper-pagination-bullet-width: 8px;
  --swiper-pagination-bullet-height: 8px;
  --swiper-pagination-bullet-inactive-color: #000;
  --swiper-pagination-bullet-inactive-opacity: 0.2;
  --swiper-pagination-bullet-opacity: 1;
  --swiper-pagination-bullet-horizontal-gap: 4px;
  --swiper-pagination-bullet-vertical-gap: 6px;
}

Parallax

Swiper supports parallax transition effects for swiper/slides nested elements. There are two types of parallax elements supported:

  • Direct child elements of swiper. Parallax effect for such elements will depend on total slider progress. Useful for parallax backgrounds

  • Slides child elements. Parallax effect for such elements will depend on slide progress

To enable parallax effects you need to init Swiper with passed parallax:true parameter and add one of the following (or mix) attributes to required elements:

  • data-swiper-parallax - enable transform-translate parallax transition. This attribute may accept: number - value in px (as for title, subtitle in example above) to move element depending on progress. In this case such element will be moved on ± this value in px depending on slide position (next or previous) percentage - (as for "parallax-bg") to move element depending on progress and on its size. In this case such element will be moved on ±this percentage of its size (width in horizontal direction, and height in vertical direction) depending on slide position (next or previous). So if element has 400px width and you specified data-swiper-parallax="50%" then it will be moved on ± 200px

  • data-swiper-parallax-x - same but for x-axis direction

  • data-swiper-parallax-y - same but for y-axis direction

  • data-swiper-parallax-scale - scale ratio of the parallax element when it is in "inactive" (not on active slide) state

  • data-swiper-parallax-opacity - opacity of the parallax element when it is in "inactive" (not on active slide) state

  • data-swiper-parallax-duration - custom transition duration for parallax elements

<div class="swiper">
  <!-- Parallax background element -->
  <div
    class="parallax-bg"
    style="background-image:url(path/to/image.jpg)"
    data-swiper-parallax="-23%"
  ></div>
  <div class="swiper-wrapper">
    <div class="swiper-slide">
      <!-- Each slide has parallax title -->
      <div class="title" data-swiper-parallax="-100">Slide 1</div>
      <!-- Parallax subtitle -->
      <div class="subtitle" data-swiper-parallax="-200">Subtitle</div>
      <!-- And parallax text with custom transition duration -->
      <div
        class="text"
        data-swiper-parallax="-300"
        data-swiper-parallax-duration="600"
      >
        <p>Lorem ipsum dolor sit amet, ...</p>
      </div>
      <!-- Opacity parallax -->
      <div data-swiper-parallax-opacity="0.5">I will change opacity</div>
      <!-- Scale parallax -->
      <div data-swiper-parallax-scale="0.15">I will change scale</div>
    </div>
    ...
  </div>
</div>

Parameters

The parallax module has a single on/off switch. The actual parallax behaviour is driven entirely by the data-swiper-parallax-* attributes you put on the slide elements (see the example above).

Object with parallax parameters or boolean true to enable with default settings.

const swiper = new Swiper('.swiper', {
  parallax: true,
});
Name Type Default Description

enabled

boolean

false

Enable, if you want to use "parallaxed" elements inside of slider

Scrollbar

Adds a scrollbar to the slider that mirrors the current position inside the full set of slides. With draggable: true the visitor can also grab the scrollbar handle and drag the slider directly — useful for sliders with many slides or with freeMode enabled.

Parameters

The table below lists the options that go inside the scrollbar object. Pass scrollbar: true to enable the module with the default settings (Swiper will then look for an element with the class .swiper-scrollbar inside the slider container).

Object with scrollbar parameters or boolean true to enable with default settings.

const swiper = new Swiper('.swiper', {
  scrollbar: {
    el: '.swiper-scrollbar',
    draggable: true,
  },
});
Name Type Default Description

dragClass

string

'swiper-scrollbar-drag'

Scrollbar draggable element CSS class

dragSize

number | 'auto'

'auto'

Size of scrollbar draggable element in px

draggable

boolean

false

Set to true to make the scrollbar draggable so the visitor can control the slider position by dragging it.

el

HTMLElement | CSSSelector | null

null

String with CSS selector or HTML element of the container with scrollbar.

enabled

boolean

true

Whether the module is active. Mainly used together with breakpoints to enable or disable the scrollbar at specific screen sizes.

hide

boolean

false

Hide scrollbar automatically after user interaction

horizontalClass

string

'swiper-scrollbar-horizontal'

CSS class name set to scrollbar in horizontal Swiper

lockClass

string

'swiper-scrollbar-lock'

Scrollbar element additional CSS class when it is disabled

scrollbarDisabledClass

string

'swiper-scrollbar-disabled'

CSS class name added on swiper container and scrollbar element when scrollbar is disabled by breakpoint

snapOnRelease

boolean

true

Set to true to snap slider position to slides when you release scrollbar

verticalClass

string

'swiper-scrollbar-vertical'

CSS class name set to scrollbar in vertical Swiper

Properties

After the slider is created, the resolved scrollbar elements are available on swiper.scrollbar:

Name Type Description

swiper.scrollbar.dragEl

HTMLElement

HTMLElement of Scrollbar draggable handler element

swiper.scrollbar.el

HTMLElement

HTMLElement of Scrollbar container element

Methods

The scrollbar module adds a few helper methods. Swiper calls them automatically while the slider runs; you only need them when you build a custom scrollbar UI on top of Swiper.

Name Description

swiper.scrollbar.destroy()

Destroy scrollbar

swiper.scrollbar.init()

Initialize scrollbar

swiper.scrollbar.setTranslate()

Updates scrollbar translate

swiper.scrollbar.updateSize()

Updates scrollbar track and handler sizes

Events

When the scrollbar is draggable, Swiper fires the following extra events while the visitor drags it. Register them with swiper.on('eventName', handler) like any other Swiper event.

Name Arguments Description

scrollbarDragEnd

(swiper, event)

Event is fired on draggable scrollbar drag end

scrollbarDragMove

(swiper, event)

Event is fired on draggable scrollbar drag move

scrollbarDragStart

(swiper, event)

Event is fired on draggable scrollbar drag start

CSS

The look of the scrollbar (track colour, handler colour, size, border radius, position relative to the slider) can be tuned through a set of CSS custom properties (CSS variables). Set them on the slider container or on :root to adjust the appearance — no JavaScript needed.

{
  --swiper-scrollbar-border-radius: 10px;
  --swiper-scrollbar-top: auto;
  --swiper-scrollbar-bottom: 4px;
  --swiper-scrollbar-left: auto;
  --swiper-scrollbar-right: 4px;
  --swiper-scrollbar-sides-offset: 1%;
  --swiper-scrollbar-bg-color: rgba(0, 0, 0, 0.1);
  --swiper-scrollbar-drag-bg-color: rgba(0, 0, 0, 0.5);
  --swiper-scrollbar-size: 4px;
}

Thumbs

In addition to the Controller module, Swiper provides a Thumbs module that is designed to keep a thumbnail strip in sync with a main slider. Thumbs handles edge cases (loop mode, multi-active thumbs, auto-scrolling the strip) in a way that is more correct for this specific use-case than the generic Controller module.

Parameters

The table below lists the options that go inside the thumbs object. The only required option is swiper, which must be set to the Swiper instance (or a CSS selector) of the thumbnail slider.

Object with thumbs component parameters

const swiper = new Swiper('.swiper', {
  ...
  thumbs: {
    swiper: thumbsSwiper
  }
});
Name Type Default Description

autoScrollOffset

number

0

Allows to set on which thumbs active slide from edge it should automatically move scroll thumbs. For example, if set to 1 and last visible thumb will be activated (1 from edge) it will auto scroll thumbs

multipleActiveThumbs

boolean

true

When enabled multiple thumbnail slides may get activated

slideThumbActiveClass

string

'swiper-slide-thumb-active'

Additional class that will be added to activated thumbs swiper slide

swiper

string | Swiper | null

null

Swiper instance of swiper used as thumbs or object with Swiper parameters to initialize thumbs swiper

thumbsContainerClass

string

'swiper-thumbs'

Additional class that will be added to thumbs swiper

Properties

After the slider is created, the linked thumbs Swiper instance is available on swiper.thumbs:

Name Type Description

swiper.thumbs.swiper

Swiper

Swiper instance of thumbs swiper

Methods

The thumbs module adds two helper methods. Swiper calls them automatically so in normal use you do not need to touch them; they are documented here for completeness.

Name Description

swiper.thumbs.init()

Initialize thumbs

swiper.thumbs.update(initial, p)

Update thumbs

Virtual Slides

Virtual Slides module allows to keep just required amount of slides in DOM. It is very useful in terms in performance and memory issues if you have a lot of slides, especially slides with heavyweight DOM tree or images.

Note that according to Virtual Slides realization it doesn’t work with Grid module and slidesPerView: 'auto'

Parameters

The table below lists the options that go inside the virtual object. The typical usage is to pass an array of slide contents as the slides parameter and Swiper will render only the slides that are currently visible.

Enables virtual slides functionality. Object with virtual slides parameters or boolean true to enable with default settings.

const swiper = new Swiper('.swiper', {
  virtual: {
    slides: ['Slide 1', 'Slide 2', 'Slide 3', 'Slide 4', 'Slide 5'],
  },
});
Name Type Default Description

addSlidesAfter

number

0

Increases amount of pre-rendered slides after active slide

addSlidesBefore

number

0

Increases amount of pre-rendered slides before active slide

cache

boolean

true

Enables DOM cache of rendering slides html elements. Once they are rendered they will be saved to cache and reused from it.

enabled

boolean

false

Whether the virtual slides are enabled

renderExternal

function(VirtualData)

null

Function for external rendering (e.g. using some other library to handle DOM manipulations and state like React.js or Vue.js). As an argument it accepts data object with the following properties:

  • offset - slides left/top offset in px

  • from - index of first slide required to be rendered

  • to - index of last slide required to be rendered

  • slides - array with slide items to be rendered

renderExternalUpdate

boolean

true

When enabled (by default) it will update Swiper layout right after renderExternal called. Useful to disable and update swiper manually when used with render libraries that renders asynchronously

renderSlide

function(T, any)

null

Function to render slide. As an argument it accepts current slide item for slides array and index number of the current slide. Function must return an outer HTML of the swiper slide or slide HTML element.

slides

T[]

Array with slides

Properties

After the slider is created, the current virtual-slides state is available on swiper.virtual:

Name Type Description

swiper.virtual.cache

object

Object with cached slides HTML elements

swiper.virtual.from

number

Index of first rendered slide

swiper.virtual.slides

Array with slide items passed by virtual.slides parameter

swiper.virtual.to

number

Index of last rendered slide

Methods

The virtual module exposes its own set of methods to add and remove slides from the virtual array at runtime. Use these instead of the generic Manipulation module methods when virtual is enabled.

Name Description

swiper.virtual.appendSlide(slide)

Append slide. slides can be a single slide item or array with such slides.

swiper.virtual.prependSlide(slide)

Prepend slide. slides can be a single slide item or array with such slides.

swiper.virtual.removeAllSlides()

Remove all slides

swiper.virtual.removeSlide(slideIndexes)

Remove specific slide or slides. slideIndexes can be a number with slide index to remove or array with indexes.

swiper.virtual.update(force)

Update virtual slides state

DOM

Since version 9, Swiper virtual slides can work with slides originally rendered in DOM. On initialize it will remove them from DOM, cache and then re-use the ones which are required:

<div class="swiper">
  <div class="swiper-wrapper">
    <div class="swiper-slide">Slide 1</div>
    <div class="swiper-slide">Slide 2</div>
    ...
    <div class="swiper-slide">Slide 100</div>
  </div>
</div>
<script>
  const swiper = new Swiper('.swiper', {
    virtual: {
      enabled: true,
    },
  });
</script>

Zoom

Swiper supports zoom images functionality (similar to what you see on iOS when browsing single photo) where you can zoom-in image by pinch gesture and or by zoom-in/out by double tap on it. In this case, additional layout is required:

<div class="swiper">
  <div class="swiper-wrapper">
    <div class="swiper-slide">
      <div class="swiper-zoom-container">
        <img src="path/to/image1.jpg" />
      </div>
    </div>
    <div class="swiper-slide">
      <div class="swiper-zoom-container">
        <img src="path/to/image2.jpg" />
      </div>
    </div>
    <div class="swiper-slide">Plain slide with text</div>
    <div class="swiper-slide">
      <!-- Override maxRatio parameter -->
      <div class="swiper-zoom-container" data-swiper-zoom="5">
        <img src="path/to/image1.jpg" />
      </div>
    </div>
  </div>
</div>
  • All "zoomable" images should be wrapped with the div with swiper-zoom-container class.

  • By default it expects to zoom one of the img, picture or canvas element. If you want to make zoom on some other custom element, then just add swiper-zoom-target class to this element.

For example:

<div class="swiper">
  <div class="swiper-wrapper">
    <div class="swiper-slide">
      <div class="swiper-zoom-container">
        <!-- custom zoomable element -->
        <div
          class="swiper-zoom-target"
          style="background-image: url(...)"
        ></div>
      </div>
    </div>
  </div>
</div>

You can override maxRatio parameter for specific slides by using data-swiper-zoom attribute on zoom container.

Parameters

The table below lists the options that go inside the zoom object. Pass zoom: true to enable the module with the default settings (max zoom of 3 times the original size, double-tap to zoom).

Enables zooming functionality. Object with zoom parameters or boolean true to enable with default settings.

const swiper = new Swiper('.swiper', {
  zoom: {
    maxRatio: 5,
  },
});
Name Type Default Description

containerClass

string

'swiper-zoom-container'

CSS class name of zoom container

limitToOriginalSize

boolean

false

When set to true, the image will not be scaled past 100% of its original size

maxRatio

number

3

Maximum image zoom multiplier

minRatio

number

1

Minimal image zoom multiplier

panOnMouseMove

boolean

false

When set to true, a zoomed in image will automatically pan while moving the mouse over the image

toggle

boolean

true

Enable/disable zoom-in by slide’s double tap

zoomedSlideClass

string

'swiper-slide-zoomed'

CSS class name of zoomed in container

Properties

After the slider is created, the current zoom state is available on swiper.zoom:

Name Type Description

swiper.zoom.enabled

boolean

Whether the zoom module is enabled

swiper.zoom.scale

number

Current image scale ratio

Methods

The zoom module exposes helper methods for controlling the zoom level from your own code — for example from a custom "zoom in" / "zoom out" button or from a keyboard shortcut.

Name Description

swiper.zoom.disable()

Disable zoom module

swiper.zoom.enable()

Enable zoom module

swiper.zoom.in(ratio)

Zoom in image of the currently active slide. Optionally accepts custom zoom ratio

swiper.zoom.out()

Zoom out image of the currently active slide

swiper.zoom.toggle(event)

Toggle image zoom of the currently active slide

Events

When the zoom module is active, Swiper fires the following extra event whenever the zoom level changes. Register it with swiper.on('eventName', handler) like any other Swiper event.

Name Arguments Description

zoomChange

(swiper, scale, imageEl, slideEl)

Event is fired on zoom change