Swiper API

Swiper Full HTML Layout

<!-- Slider main container -->
<div class="swiper-container">
    <!-- 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>

Initialize Swiper

Now, when we have Swiper's HTML, we need to initialize it using the following function:

new Swiper(swiperContainer, parameters) - initialize swiper with options

  • swiperContainer - HTMLElement or string (with CSS Selector) of swiper container HTML element. Required.
  • parameters - object - object with Swiper parameters. Optional.
  • Method returns initialized Swiper instance

For example:

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

After you initialize Swiper it is possible to access to Swiper's instance on its HTMLElement. It is swiper property of Swiper's HTML container element:

var mySwiper = documet.querySelector('.swiper-container').swiper
 
// Now you can use all slider methods like
mySwiper.slideNext();

Swiper Parameters

Let's look on list of all available parameters:

Parameter Type Default Description
init boolean true Whether Swiper should be initialised automatically when you create an instance. If disabled, then you need to init it manually by calling mySwiper.init()
initialSlide number 0 Index number of initial slide.
direction string 'horizontal' Could be 'horizontal' or 'vertical' (for vertical slider).
speed number 300 Duration of transition between slides (in ms)
setWrapperSize boolean false Enabled this option and plugin will set width/height on swiper wrapper equal to total size of all slides. Mostly should be used as compatibility fallback option for browser that don't support flexbox layout well
virtualTranslate boolean false Enabled this option and swiper will be operated as usual except it will not move, real translate values on wrapper will not be set. Useful when you may need to create custom slide transition
width number Swiper width (in px). Parameter allows to force Swiper width. Useful only if you initialize Swiper when it is hidden.
Setting this parameter will make Swiper not responsive
height number Swiper height (in px). Parameter allows to force Swiper height. Useful only if you initialize Swiper when it is hidden.
Setting this parameter will make Swiper not responsive
autoHeight boolean false Set to true and slider wrapper will adopt its height to the height of the currently active slide
roundLengths boolean false Set to true to round values of slides width and height to prevent blurry texts on usual resolution screens (if you have such)
nested boolean false Set to true on nested Swiper for correct touch events interception. Use only on nested swipers that use same direction as the parent one
uniqueNavElements boolean true If enabled (by default) and navigation elements' parameters passed as a string (like ".pagination") then Swiper will look for such elements through child elements first. Applies for pagination, prev/next buttons and scrollbar elements
effect string 'slide' Tranisition effect. Could be "slide", "fade", "cube", "coverflow" or "flip"
runCallbacksOnInit boolean true Fire [Transition/SlideChange][Start/End] events on swiper initialization. Such events will be fired on initialization in case of your initialSlide is not 0, or you use loop mode
on object Register event handlers
Slides grid
spaceBetween number 0 Distance between slides in px.
slidesPerView number or 'auto' 1

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

If you use it with "auto" value and along with loop: true then you need to specify loopedSlides parameter with amount of slides to loop (duplicate)

slidesPerView: 'auto' is currently not compatible with multirow mode, when slidesPerColumn > 1

slidesPerColumn number 1 Number of slides per column, for multirow layout
slidesPerColumnFill string 'column' Could be 'column' or 'row'. Defines how slides should fill rows, by column or by row
slidesPerGroup number 1 Set numbers of slides to define and enable group sliding. Useful to use with slidesPerView > 1
centeredSlides boolean false If true, then active slide will be centered, not always on the left side.
slidesOffsetBefore number 0 Add (in px) additional slide offset in the beginning of the container (before all slides)
slidesOffsetAfter number 0 Add (in px) additional slide offset in the end of the container (after all slides)
normalizeSlideIndex boolean true Normalize slide index. See #1766
Grab Cursor
grabCursor boolean false This option may a little improve desktop usability. If true, user will see the "grab" cursor when hover on Swiper
Touches
touchEventsTarget string 'container' Target element to listen touch events on. Can be 'container' (to listen for touch events on swiper-container) or 'wrapper' (to listen for touch events on swiper-wrapper)
touchRatio number 1 Touch ration
touchAngle number 45 Allowable angle (in degrees) to trigger touch move
simulateTouch boolean true If true, Swiper will accept mouse events like touch events (click and drag to change slides)
shortSwipes boolean true Set to false if you want to disable short swipes
longSwipes boolean true Set to false if you want to disable long swipes
longSwipesRatio number 0.5 Ratio to trigger swipe to next/previous slide during long swipes
longSwipesMs number 300 Minimal duration (in ms) to trigger swipe to next/previous slide during long swipes
followFinger boolean true If disabled, then slider will be animated only when you release it, it will not move while you hold your finger on it
allowTouchMove boolean true If false, then the only way to switch the slide is use of external API functions like slidePrev or slideNext
threshold number 0 Threshold value in px. If "touch distance" will be lower than this value then swiper will not move
touchMoveStopPropagation boolean true If enabled, then propagation of "touchmove" will be stopped
iOSEdgeSwipeDetection boolean false Enable to release Swiper events for swipe-to-go-back work in iOS UIWebView
iOSEdgeSwipeThreshold number 20 Area (in px) from left edge of the screen to release touch events for swipe-to-go-back in iOS UIWebView
touchReleaseOnEdges boolean false Enable to release touch events on slider edge position (beginning, end) to allow for further page scrolling
passiveListeners boolean true Passive event listeners will be used by default where possible to improve scrolling performance on mobile devices. But if you need to use `e.preventDefault` and you have conflict with it, then you should disable this parameter
Touch Resistance
resistance boolean true Set to false if you want to disable resistant bounds
resistanceRatio number 0.85 This option allows you to control resistance ratio
Swiping / No swiping
allowSlidePrev boolean true Set to false to disable swiping to previous slide direction (to left or top)
allowSlideNext boolean true Set to false to disable swiping to next slide direction (to right or bottom)
noSwiping boolean true Will disable swiping on elements matched to class specified in noSwipingClass
noSwipingClass string 'swiper-no-swiping' If true, then you can add noSwipingClass class to swiper's slide to prevent/disable swiping on this element
swipeHandler string / HTMLElement null String with CSS selector or HTML element of the container with pagination that will work as only available handler for swiping
Clicks
preventClicks boolean true Set to true to prevent accidental unwanted clicks on links during swiping
preventClicksPropagation boolean true Set to true to stop clicks event propagation on links during swiping
slideToClickedSlide boolean false Set to true and click on any slide will produce transition to this slide
Freemode
freeMode boolean false If true then slides will not have fixed positions
freeModeMomentum boolean true If true, then slide will keep moving for a while after you release it
freeModeMomentumRatio number 1 Higher value produces larger momentum distance after you release slider
freeModeMomentumVelocityRatio number 1 Higher value produces larger momentum velocity after you release slider
freeModeMomentumBounce boolean true Set to false if you want to disable momentum bounce in free mode
freeModeMomentumBounceRatio number 1 Higher value produces larger momentum bounce effect
freeModeMinimumVelocity number 0.02 Minimum touchmove-velocity required to trigger free mode momentum
freeModeSticky boolean false Set to true to enable snap to slides positions in free mode
Progress
watchSlidesProgress boolean false Enable this feature to calculate each slides progress
watchSlidesVisibility boolean false watchSlidesProgress should be enabled. Enable this option and slides that are in viewport will have additional visible class
Images
preloadImages boolean true When enabled Swiper will force to load all images
updateOnImagesReady boolean true When enabled Swiper will be reinitialized after all inner images (<img> tags) are loaded. Required preloadImages: true
Loop
loop boolean false

Set to true to enable continuous loop mode

If you use it along with slidesPerView: 'auto' then you need to specify loopedSlides parameter with amount of slides to loop (duplicate)

Also, because of nature of how the loop mode works, it will add duplicated slides. Such duplicated classes will have additional classes:

  • swiper-slide-duplicate - represents duplicated slide
  • swiper-slide-duplicate-active - represents slide duplicated to the currently active slide
  • swiper-slide-duplicate-next - represents slide duplicated to the slide next to active
  • swiper-slide-duplicate-prev - represents slide duplicated to the slide previous to active
loopAdditionalSlides number 0 Addition number of slides that will be cloned after creating of loop
loopedSlides number null If you use slidesPerView:'auto' with loop mode you should tell to Swiper how many slides it should loop (duplicate) using this parameter
loopFillGroupWithBlank boolean false Enable and loop mode will fill groups with insufficient number of slides with blank slides. Good to be used with slidesPerGroup parameter
Breakpoints
breakpoints object Allows to set different parameter for different responsive breakpoints (screen sizes). Not all parameters can be changed in breakpoints, only those which are not required different layout and logic, like slidesPerView, slidesPerGroup, spaceBetween. Such parameters like slidesPerColumn, loop, direction, effect won't work. For example:
var swiper = new Swiper('.swiper-container', {
  // Default parameters
  slidesPerView: 4,
  spaceBetween: 40,
  // Responsive breakpoints
  breakpoints: {
    // when window width is <= 320px
    320: {
      slidesPerView: 1,
      spaceBetween: 10
    },
    // when window width is <= 480px
    480: {
      slidesPerView: 2,
      spaceBetween: 20
    },
    // when window width is <= 640px
    640: {
      slidesPerView: 3,
      spaceBetween: 30
    }
  }
})
Observer
observer boolean false Set to true to enable Mutation Observer on Swiper and its elements. In this case Swiper will be updated (reinitialized) each time if you change its style (like hide/show) or modify its child elements (like adding/removing slides)
observeParents boolean false Set to true if you also need to watch Mutations for Swiper parent elements
Namespace
containerModifierClass string 'swiper-container-' The beginning of the modifier CSS class that can be added to swiper container depending on different parameters
slideClass string 'swiper-slide' CSS class name of slide
slideActiveClass string 'swiper-slide-active' CSS class name of currently active slide
slideDuplicatedActiveClass string 'swiper-slide-duplicate-active' CSS class name of duplicated slide which represents the currently active slide
slideVisibleClass string 'swiper-slide-visible' CSS class name of currently visible slide
slideDuplicateClass string 'swiper-slide-duplicate' CSS class name of slide duplicated by loop mode
slideNextClass string 'swiper-slide-next' CSS class name of slide which is right after currently active slide
slideDuplicatedNextClass string 'swiper-slide-duplicate-next' CSS class name of duplicated slide which represents the slide next to active slide
slidePrevClass string 'swiper-slide-prev' CSS class name of slide which is right before currently active slide
slideDuplicatedPrevClass string 'swiper-slide-duplicate-prev' CSS class name of duplicated slide which represents the slide previous to active slide
wrapperClass string 'swiper-wrapper' CSS class name of slides' wrapper

Slider Methods & Properties

After we initialize Slider we have its initialized instance in variable (like mySwiper variable in example above) with helpful methods and properties:

Properties
mySwiper.params Object with passed initialization parameters
mySwiper.$el Dom7 element with slider container HTML element. To get vanilla HTMLElement use mySwiper.el
mySwiper.$wrapperEl Dom7 element with slider wrapper HTML element. To get vanilla HTMLElement use mySwiper.wrapperEl
mySwiper.slides Dom7 array-like collection of slides HTML elements. To get specific slide HTMLElement use mySwiper.slides[1]
mySwiper.width Width of container
mySwiper.height Height of container
mySwiper.translate Current value of wrapper translate
mySwiper.progress Current progress of wrapper translate (from 0 to 1)
mySwiper.activeIndex

Index number of currently active slide

Note, that in loop mode active index value will be always shifted on a number of looped/duplicated slides

mySwiper.realIndex

Index number of currently active slide considering duplicated slides in loop mode

mySwiper.previousIndex Index number of previously active slide
mySwiper.isBeginning true if slider on most "left"/"top" position
mySwiper.isEnd true if slider on most "right"/"bottom" position
mySwiper.animating true if swiper is in transition
mySwiper.touches Object with the following touch event properties:
  • mySwiper.touches.startX
  • mySwiper.touches.startY
  • mySwiper.touches.currentX
  • mySwiper.touches.currentY
  • mySwiper.touches.diff
mySwiper.clickedIndex Index number of last clicked slide
mySwiper.clickedSlide Link to last clicked slide (HTMLElement)
mySwiper.allowSlideNext Disable / enable ability to slide to the next slides by assigning false/true to this property
mySwiper.allowSlidePrev Disable / enable ability to slide to the previous slides by assigning false/true to this property
mySwiper.allowTouchMove Disable / enable ability move slider by grabbing it with mouse or by touching it with finger (on touch screens) by assigning false/true to this property
Methods
mySwiper.slideNext(speed, runCallbacks); Run transition to next slide
  • speed - number - transition duration (in ms). Optional
  • runCallbacks - boolean - Set it to false (by default it is true) and transition will not produce transition events. Optional
mySwiper.slidePrev(speed, runCallbacks); Run transition to previous slide
  • speed - number - transition duration (in ms). Optional
  • runCallbacks - boolean - Set it to false (by default it is true) and transition will not produce transition events. Optional
mySwiper.slideTo(index, speed, runCallbacks); Run transition to the slide with index number equal to 'index' parameter for the duration equal to 'speed' parameter.
  • index - number - index number of slide
  • speed - number - transition duration (in ms). Optional
  • runCallbacks - boolean - Set it to false (by default it is true) and transition will not produce transition events. Optional
mySwiper.update();

You should call it after you add/remove slides manually, or after you hide/show it, or do any custom DOM modifications with Swiper

This method also includes subcall of the following methods which you can use separately:

  • mySwiper.updateSize() - recalculate size of swiper container
  • mySwiper.updateSlides() - recalculate number of slides and their offsets. Useful after you add/remove slides with JavaScript
  • mySwiper.updateProgress() - recalculate swiper progress
  • mySwiper.updateSlidesClasses() - update active/prev/next classes on slides and bullets
mySwiper.detachEvents(); Detach all events listeners
mySwiper.attachEvents(); Atach all events listeners again
mySwiper.destroy(deleteInstance, cleanStyles); Destroy slider instance and detach all events listeners, where
  • deleteInstance - boolean - Set it to false (by default it is true) to not to delete Swiper instance
  • cleanStyles - boolean - Set it to true (by default it is true) and all custom styles will be removed from slides, wrapper and container. Useful if you need to destroy Swiper and to init again with new options or in different direction
mySwiper.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:
mySwiper.appendSlide('<div class="swiper-slide">Slide 10"</div>')
mySwiper.appendSlide([
   '<div class="swiper-slide">Slide 10"</div>', 
   '<div class="swiper-slide">Slide 11"</div>'
]);
mySwiper.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:
mySwiper.prependSlide('<div class="swiper-slide">Slide 0"</div>')
mySwiper.prependSlide([
   '<div class="swiper-slide">Slide 1"</div>', 
   '<div class="swiper-slide">Slide 2"</div>'
]);
mySwiper.removeSlide(slideIndex); Remove selected slides. slideIndex could be a number with slide index to remove or array with indexes, for example:
mySwiper.removeSlide(0); //remove first slide
mySwiper.removeSlide([0, 1]); //remove first and second slides
mySwiper.removeAllSlides(); Remove all slides
mySwiper.setTranslate(translate); Set custom css3 transform's translate value for swiper wrapper
mySwiper.getTranslate(); Get current value of swiper wrapper css3 transform translate
mySwiper.on(event, handler) Add event listener
mySwiper.once(event, handler) Add event listener that will be executed only once
mySwiper.off(event, handler) Remove event listener for specified event
mySwiper.off(event) Remove all listeners for specified event
mySwiper.disableMousewheelControl(); Disable mousewheel control
mySwiper.enableMousewheelControl(); Enable mousewheel control
mySwiper.disableKeyboardControl(); Disable keyboard control
mySwiper.enableKeyboardControl(); Enable keyboard control
mySwiper.unsetGrabCursor(); Unset grab cursor
mySwiper.setGrabCursor(); Set grab cursor

Events

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

  1. Using on parameter on swiper initialization:

    var mySwiper = new Swiper('.swiper-container', {
      // ...
      on: {
        init: function () {
          console.log('swiper initialized');
        },
      },
    };

  2. Using on method after swiper initialization.

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

Please note, that this keyword within event handler always points to Swiper instance


Event name Arguments Description
init

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

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

Otherwise use it as the parameter:

var swiper = new Swiper('.swiper-container', {
  // other parameters
  on: {
    init: function () {
      /* do something */
    },
  }
});
beforeDestroy Event will be fired right beforey Swiper destoryed
slideChange Event will be fired when currently active slide is changed
slideChangeTransitionStart Event will be fired in the beginning of animation to other slide (next or previous).
slideChangeTransitionEnd Event will be fired after animation to other slide (next or previous).
slideNextTransitionStart Same as "slideChangeTransitionStart" but for "forward" direction only
slideNextTransitionEnd Same as "slideChangeTransitionEnd" but for "forward" direction only
slidePrevTransitionStart Same as "slideChangeTransitionStart" but for "backward" direction only
slidePrevTransitionEnd Same as "slideChangeTransitionEnd" but for "backward" direction only
transitionStart Event will be fired in the beginning of transition.
transitionEnd Event will be fired after transition.
touchStart event Event will be fired when user touch Swiper. Receives 'touchstart' event as an arguments.
touchMove(event) event Event will be fired when user touch and move finger over Swiper. Receives 'touchmove' event as an arguments.
touchMoveOpposite event Event will be fired when user touch and move finger over Swiper in direction opposite to direction parameter. Receives 'touchmove' event as an arguments.
sliderMove event Event will be fired when user touch and move finger over Swiper and move it. Receives 'touchmove' event as an arguments.
touchEnd event Event will be fired when user release Swiper. Receives 'touchend' event as an arguments.
click event Event will be fired when user click/tap on Swiper after 300ms delay. Receives 'touchend' event as an arguments.
tap event Event will be fired when user click/tap on Swiper. Receives 'touchend' event as an arguments.
doubleTap event Event will be fired when user double tap on Swiper's container. Receives 'touchend' event as an arguments
imagesReady Event will be fired right after all inner images are loaded. updateOnImagesReady should be also enabled
progress progress Event will be fired when Swiper progress is changed, as an arguments it receives progress that is always from 0 to 1
reachBeginning Event will be fired when Swiper reach its beginning (initial position)
reachEnd Event will be fired when Swiper reach last slide
fromEdge Event will be fired when Swiper goes from beginning or end position
setTranslate translate Event will be fired when swiper's wrapper change its position. Receives current translate value as an arguments
setTransition transition Event will be fired everytime when swiper starts animation. Receives current transition duration (in ms) as an arguments
resize Event will be fired on window resize right before swiper's onresize manipulation

Components

Parameter Type Default Description
navigation object

Object with navigation parameters. For example:

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

{
nextEl string / HTMLElement null String with CSS selector or HTML element of the element that will work like "next" button after click on it
prevEl string / HTMLElement null String with CSS selector or HTML element of the element that will work like "prev" button after click on it
hideOnClick boolean false Toggle navigation buttons visibility after click on Slider's container
disabledClass string 'swiper-button-disabled' CSS class name added to navigation button when it becomes disabled
hiddenClass string 'swiper-button-hidden' CSS class name added to navigation button when it becomes hidden
}
Properties
mySwiper.navigation.nextEl HTMLElement of "next" navigation button
mySwiper.navigation.prevEl HTMLElement of "previous" navigation button
Methods
mySwiper.navigation.update(); Update navigation buttons state (enabled/disabled)

Pagination

Pagination Parameters

Parameter Type Default Description
pagination object

Object with navigation parameters. For example:

var mySwiper = new Swiper('.swiper-container', {
  pagination: {
    el: '.swiper-pagination',
    type: 'bullets',
  },
});

{
el string null String with CSS selector or HTML element of the container with pagination
type string 'bullets' String with type of pagination. Can be "bullets", "fraction", "progressbar" or "custom"
bulletElement string 'span' Defines which HTML tag will be use to represent single pagination bullet. Only for bullets pagination type.
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.
hideOnClick boolean true Toggle (hide/true) pagination container visibility after click on Slider's container
clickable boolean false If true then clicking on pagination button will cause transition to appropriate slide. Only for bullets pagination type
renderBullet function(index, className) 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

For example, with this code, we can add slide number into pagination bullet:

var swiper = new Swiper('.swiper-container', {
  //...
  renderBullet: function (index, className) {
    return '<span class="' + className + '">' + (index + 1) + '</span>';
  }
});
renderFraction function(currentClass, totalClass) null This parameter allows to customize "fraction" pagination html. Only for fraction pagination type

For example:

var swiper = new Swiper('.swiper-container', {
  //...
  renderFraction: function (currentClass, totalClass) {
      return '<span class="' + currentClass + '"></span>' +
             ' of ' +
             '<span class="' + totalClass + '"></span>';
  }
});
renderProgressbar function(progressbarFillClass) null This parameter allows to customize "progress" pagination. Only for progress pagination type

For example:

var swiper = new Swiper('.swiper-container', {
  //...
  renderProgressbar: function (progressbarFillClass) {
      return '<span class="' + progressbarFillClass + '"></span>';
  }
});
renderCustom function(swiper, current, total) null This parameter is required for custom pagination type where you have to specify how it should be rendered

For example:

var swiper = new Swiper('.swiper-container', {
  //...
  renderCustom: function (swiper, current, total) {
      return current + ' of ' + total;
  }
});
bulletClass string 'swiper-pagination-bullet' CSS class name of single pagination bullet
bulletActiveClass string 'swiper-pagination-bullet-active' CSS class name of currently active pagination bullet
modifierClass string 'swiper-pagination-' The beginning of the modifier CSS class name that will be added to pagination depending on parameters
currentClass string 'swiper-pagination-current' CSS class name of the element with currently active index in "fraction" pagination
totalClass string 'swiper-pagination-total' CSS class name of the element with total number of "snaps" in "fraction" pagination
hiddenClass string 'swiper-pagination-hidden' CSS class name of pagination when it becomes inactive
progressbarFillClass string 'swiper-pagination-progressbar-fill' CSS class name of pagination progressbar fill element
clickableClass string 'swiper-pagination-clickable' CSS class name set to pagination when it is clickable
}

Pagination Methods & Properties

Properties
mySwiper.pagination.el HTMLElement of pagination container element
mySwiper.pagination.bullets Dom7 array-like collection of pagination bullets HTML elements. To get specific slide HTMLElement use mySwiper.pagination.bullets[1]
Methods
mySwiper.pagination.render(); Render pagination layout
mySwiper.pagination.update(); Update pagination state (enabled/disabled/active)

Scrollbar

Scrollbar Parameters

Parameter Type Default Description
scrollbar object

Object with scrollbar parameters. For example:

var mySwiper = new Swiper('.swiper-container', {
  scrollbar: {
    el: '.swiper-scrollbar',
    draggable: true,
  },
});

{
el string / HTMLElement null String with CSS selector or HTML element of the container with scrollbar.
hide boolean true Hide scrollbar automatically after user interaction
draggable boolean false Set to true to enable make scrollbar draggable that allows you to control slider position
snapOnRelease boolean false Set to true to snap slider position to slides when you release scrollbar
dragSize string/number 'auto' Size of scrollbar draggable element in px
}

Scrollbar Methods & Properties

Properties
mySwiper.scrollbar.el HTMLElement of Scrollbar container element
mySwiper.scrollbar.dragEl HTMLElement of Scrollbar draggable handler element
Methods
mySwiper.scrollbar.updateSize(); Updates scrollbar track and handler sizes

Autoplay

Autoplay Parameters

Parameter Type Default Description
autoplay object/boolean

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

var mySwiper = new Swiper('.swiper-container', {
  autoplay: {
    delay: 5000,
  },
});

{
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 specifi 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">
stopOnLast boolean false Enable this parameter and autoplay will be stopped when it reaches last slide (has no effect in loop mode)
disableOnInteraction boolean true Set to false and autoplay will not be disabled after user interactions (swipes), it will be restarted every time after interaction
}

Autoplay Methods & Properties

Properties
mySwiper.autoplay.running Whether autoplay enabled and running
Methods
mySwiper.autoplay.start(); Start autoplay
mySwiper.autoplay.stop(); Stop autoplay

Autoplay Events

Event name Arguments Description
autoplayStart Event will be fired in when autoplay started
autoplayStop Event will be fired when autoplay stopped
autoplay Event will be fired when slide changed with autoplay

Parallax

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

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:

<div class="swiper-container">
    <!-- Parallax background element -->
    <div
        class="parallax-bg"
        style="background-image:url(http://lorempixel.com/900/600/nightlife/2/)"
        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>

Parallax Parameters

Parameter Type Default Description
parallax boolean false Enable, if you want to use "parallaxed" elements inside of slider

Lazy Loading

To enable lazy loading, first of all we need special layout for images or elements with backround in slides:

<div class="swiper-container">
    <div class="swiper-wrapper">

        <!-- Lazy image -->
        <div class="swiper-slide">
            <img data-src="path/to/picture-1.jpg" class="swiper-lazy">
            <div class="swiper-lazy-preloader"></div>
        </div>

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

        <!-- Element with lazy background image -->
        <div class="swiper-slide">
            <div data-background="path/to/picture-2.jpg" class="swiper-lazy">
                <div class="swiper-lazy-preloader"></div>
            </div>
        </div>

        <!-- Lazy background image on slide itself -->
        <div data-background="path/to/picture-3.jpg" class="swiper-slide swiper-lazy">
            <div class="swiper-lazy-preloader"></div>
        </div>
    </div>
</div>

As you see:

You may also 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>

After that we need to enable lazy loading on Swiper initialization:

var swiper = new Swiper('.swiper-container', {
    // Disable preloading of all images
    preloadImages: false,
    // Enable lazy loading
    lazy: true
});

If you use slidesPerView "auto" or slidesPerView > 1, then you should also enable watchSlidesVisibility and Swiper will load images in currently visible slides

Lazy Loading Parameters

Parameter Type Default Description
lazy object/boolean

Enables images lazy loading. Object with lazy loading parameters or boolean true to enable with default settings. For example:

var mySwiper = new Swiper('.swiper-container', {
  lazy: {
    loadPrevNext: true,
  },
});

{
loadPrevNext boolean false Set to "true" to enable lazy loading for the closest slides images (for previous and next slide images)
loadPrevNextAmount number 1 Amount of next/prev slides to preload lazy images in. Can't be less than slidesPerView
loadOnTransitionStart boolean false By default, Swiper will load lazy images after transition to this slide, so you may enable this parameter if you need it to start loading of new image in the beginning of transition
elementClass string 'swiper-lazy' CSS class name of lazy element
loadingClass string 'swiper-lazy-loading' CSS class name of lazy loading element
loadedClass string 'swiper-lazy-loaded' CSS class name of lazy loaded element
preloaderClass string 'swiper-lazy-preloader' CSS class name of lazy preloader
}

Lazy Loading Methods & Properties

Methods
mySwiper.lazy.load(); Load/update lazy images based on current slider state (position)
mySwiper.lazy.loadInSlide(index); Force to load lazy images in slide by specified index
  • index - number - index number of slide to load lazy images in

Lazy Loading Events

Event name Arguments Description
lazyImageLoad slideEl, imageEl Event will be fired in the beginning of lazy loading of image
lazyImageReady Event will be fired when lazy loading image will be loaded

Fade Effect

Fade Effect Parameters

Parameter Type Default Description
fadeEffect object

Object with Fade-effect parameters. For example:

var mySwiper = new Swiper('.swiper-container', {
  fadeEffect: {
    crossFade: true
  },
});

{
crossFade boolean false Enables slides cross fade
}

Coverflow Effect

Coverflow Effect Parameters

Parameter Type Default Description
cubeEffect object

Object with Coverflow-effect parameters. For example:

var mySwiper = new Swiper('.swiper-container', {
  coverflowEffect: {
    rotate: 30,
    slideShadows: false,
  },
});

{
slideShadows boolean true Enables slides shadows
rotate number 50 Slide rotate in degrees
stretch number 0 Stretch space between slides (in px)
depth number 100 Depth offset in px (slides translate in Z axis)
modifier number 1 Effect multipler
}

Flip Effect

Flip Effect Parameters

Parameter Type Default Description
cubeEffect object

Object with Flip-effect parameters. For example:

var mySwiper = new Swiper('.swiper-container', {
  flipEffect: {
    rotate: 30,
    slideShadows: false,
  },
});

{
slideShadows boolean true Enables slides shadows
limitRotation boolean true Limit edge slides rotation
}

Cube Effect

Cube Effect Parameters

Parameter Type Default Description
cubeEffect object

Object with Cube-effect parameters. For example:

var mySwiper = new Swiper('.swiper-container', {
  cubeEffect: {
    slideShadows: false,
  },
});

{
slideShadows boolean true Enables slides shadows
shadow boolean true Enables main slider shadow
shadowOffset number 20 Main shadow offset in px
shadowScale number 0.94 Main shadow scale ratio
}

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-container">
    <div class="swiper-wrapper">
        <div class="swiper-side">
            <div class="swiper-zoom-container">
                <img src="path/to/image1.jpg">
            </div>
        </div>
        <div class="swiper-side">
            <div class="swiper-zoom-container">
                <img src="path/to/image2.jpg">
            </div>
        </div>
        <div class="swiper-side">Plain slide with text</div>
        <div class="swiper-side">
            <!-- 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. Note, it doesn't support to zoom anything else except single image.

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

Zoom Parameters

Parameter Type Default Description
zoom object/boolean

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

var mySwiper = new Swiper('.swiper-container', {
  zoom: {
    maxRatio: 5,
  },
});

{
maxRatio number 3 Maximum image zoom multiplier
minRatio number 1 Minimal image zoom multiplier
toggle boolean true Enable/disable zoom-in by slide's double tap
containerClass string 'swiper-zoom-container' CSS class name of zoom container
zoomedSlideClass string 'swiper-slide-zoomed' CSS class name of zoomed in container
}

Zoom Methods & Properties

Properties
mySwiper.zoom.enabled Whether the zoom module is enabled
mySwiper.zoom.scale Current image scale ratio
Methods
mySwiper.zoom.enable(); Enable zoom module
mySwiper.zoom.disable(); Disable zoom module
mySwiper.zoom.toggle(); Toggle image zoom of the currently active slide
mySwiper.zoom.in(); Zoom in image of the currently active slide
mySwiper.zoom.in(); Zoom out image of the currently active slide
mySwiper.zoom.in(); Toggle image zoom of the currently active slide

Keyboard Control

Keyboard Control Parameters

Parameter Type Default Description
keyboard boolean false Set to true to enable navigation through slides using keyboard right and left (for horizontal mode), top and borrom (for vertical mode) keyboard arrows

Keyboard Methods & Properties

Properties
mySwiper.keyboard.enabled Whether the keyboard control is enabled
Methods
mySwiper.keyboard.enable(); Enable keyboard control
mySwiper.keyboard.disable(); Disable keyboard control

Mousewheel Control

Mousewheel Control Parameters

Parameter Type Default Description
mousewheel object/boolean false

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

var mySwiper = new Swiper('.swiper-container', {
  mousewheel: {
    invert: true,
  },
});

{
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.
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)
invert boolean false Set to true to invert sliding direction
sensitivity number 1 Multiplier of mousewheel data, allows to tweak mouse wheel sensitivity
eventsTarged string / HTMLElement 'container' String with CSS selector or HTML element of the container accepting mousewheel events. By default it is swiper-container
}

Mousewheel Methods & Properties

Properties
mySwiper.mousewheel.enabled Whether the mousewheel control is enabled
Methods
mySwiper.mousewheel.enable(); Enable mousewheel control
mySwiper.mousewheel.disable(); Disable mousewheel control

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 loop mode, slidesPerRow more than 1 and slidesPerView: 'auto'

Virtaul Slides Parameters

Parameter Type Default Description
zoom object/boolean

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

var mySwiper = new Swiper('.swiper-container', {
  virtual: {
    slides: ['Slide 1', 'Slide 2', 'Slide 3', 'Slide 4', 'Slide 5'],
  },
});

{
slides array [] Array with slides
cache boolean true Enables DOM cache of rendering slides html elements. Once they are rendered they will be saved to cache and resued from it.
renderSlide function(slide, index) 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 outter HTML of the swiper slide.
renderExternal function(data) null Function for external rendering (e.g. using some other library to handle DOM manipulations and state like React 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
}

Virutal Slides Methods & Properties

Properties
mySwiper.virtual.cache Object with cached slides HTML elements
mySwiper.virtual.from Index of first rendered slide
mySwiper.virtual.to Index of last rendered slide
mySwiper.virtual.slides Array with slide items passed by vlirtual.slides parameter
Methods
mySwiper.virtual.appendSlide(slide); Append slide
mySwiper.virtual.prependSlide(slide); Prepend slide
mySwiper.virtual.update(); Update virutal slides state

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-container">
    <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>
var swiper = new Swiper('.swiper-container', {
  //enable hash navigation
  hashNavigation: true
})

Hash Navigation Parameters

Parameter Type Default Description
hashNavigation object/boolean

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

var mySwiper = new Swiper('.swiper-container', {
  hashNavigation: {
    replaceState: true,
  },
});

{
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
replaceState boolean false Works in addition to hashnav to replace current url state with the new one instead of adding it to history
}

History Navigation

History Navigation Parameters

Parameter Type Default Description
history object/boolean

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. For example:

var mySwiper = new Swiper('.swiper-container', {
  history: {
    replaceState: true,
  },
});
<!-- will produce "slides/slide1" url in browser history -->
<div class="swiper-slide" data-history="slide1"></div>
{
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
key string 'slides' Url key for slides
}

Controller

Controller Parameters

Parameter Type Default Description
controller object/boolean

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

var mySwiper = new Swiper('.swiper-container', {
  controller: {
    inverse: true,
  },
});

{
control [Swiper Instance] undefined Pass here another Swiper instance or array with Swiper instances that should be controlled by this Swiper
inverse boolean false Set to true and controlling will be in inverse direction
by string 'slide' Can be 'slide' or 'container'. 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)
}

Accessibility (a11y)

Accessibility Parameters

Parameter Type Default Description
a11y object/boolean

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

var mySwiper = new Swiper('.swiper-container', {
  a11y: {
    prevSlideMessage: 'Previous slide',
    nextSlideMessage: 'Next slide',
  },
});

{
prevSlideMessage string 'Previous slide' Message for screen readers for previous button
nextSlideMessage string 'Next slide' Message for screen readers for next button
firstSlideMessage string 'This is the first slide' Message for screen readers for previous button when swiper is on first slide
lastSlideMessage string 'This is the last slide' Message for screen readers for previous button when swiper is on last slide
paginationBulletMessage string 'Go to slide {{index}}' Message for screen readers for single pagination bullet
notificationClass string 'swiper-notification' CSS class name of a11 notification
{

Custom Build

You have two options of making custom version of Swiper.

1. Using ES-module

If you use bundler with ES-modules support in your project you can import only the modules you need:

// Import Swiper and modules
import { Swiper, Navigation, Pagination, Scrollbar } from 'swiper/dist/js/swiper.esm.js';

// Install modules
Swiper.use([Navigation, Pagination, Scrollbar]);

// Now you can use Swiper
var swiper = new Swiper('.swiper-container', {
  speed: 500,
  navigation: {
    nextEl: '.swiper-button-next',
    prevEl: '.swiper-button-prev',
  },
  // ...
});

The following modules are exported from swiper.esm.js:

2. Using Build Script

Swiper comes with gulp builder that allows to build custom library version where you may include only required modules. We need the following:

  1. Download and unzip Swiper GitHub repository to local folder
  2. Install Node.js (if not installed)
  3. Install Gulp (if not installed) by executing the following command in terminal:
    $ npm install --global gulp
  4. Now, we need to install required dependencies. Go to the folder with downloaded and unzipped Swiper repository and execute in terminal:
    $ npm install
  5. Open scripts/build-config.js file:
    module.exports = {
      // remove components you don't need
      components: [
        'virtual',
        'keyboard',
        'mousewheel',
        'navigation',
        'pagination',
        'scrollbar',
        'parallax',
        'zoom',
        'lazy',
        'controller',
        'a11y',
        'history',
        'hash-navigation',
        'autoplay',
        'effect-fade',
        'effect-cube',
        'effect-flip',
        'effect-coverflow',
      ],
      // target device, can be "desktop" or "universal"
      target: 'universal',
      // default color of navigation elements
      themeColor: '#007aff',
      // additional color to be included
      colors: {
        white: '#ffffff',
        black: '#000000',
      },
    };
  6. Now, we are ready to build custom version of Swiper:
    $ npm run build:prod
  7. That is all. Generated CSS and JS files and their minified versions will be available in dist/ folder.