Swiper API

Improve this Doc

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 = document.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:

ParameterTypeDefaultDescription
initbooleantrueWhether Swiper should be initialised automatically when you create an instance. If disabled, then you need to init it manually by calling mySwiper.init()
updateOnWindowResizebooleantrueSwiper will recalculate slides position on window resize (orientationchange)
initialSlidenumber0Index number of initial slide.
directionstring'horizontal'Could be 'horizontal' or 'vertical' (for vertical slider).
speednumber300Duration of transition between slides (in ms)
setWrapperSizebooleanfalseEnabled 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
virtualTranslatebooleanfalseEnabled 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
widthnumberSwiper 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
heightnumberSwiper 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
autoHeightbooleanfalseSet to true and slider wrapper will adopt its height to the height of the currently active slide
roundLengthsbooleanfalseSet to true to round values of slides width and height to prevent blurry texts on usual resolution screens (if you have such)
nestedbooleanfalseSet to true on nested Swiper for correct touch events interception. Use only on nested swipers that use same direction as the parent one
uniqueNavElementsbooleantrueIf 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
effectstring'slide'Tranisition effect. Could be "slide", "fade", "cube", "coverflow" or "flip"
runCallbacksOnInitbooleantrueFire [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
watchOverflowbooleanfalseWhen enabled Swiper will be disabled and hide navigation buttons on case there are not enough slides for sliding
onobjectRegister event handlers
CSS Scroll Snap
cssModebooleanfalse

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

This is what is not supported when it is enabled:

  • All effects (Fade, Coverflow, Flip, Cube)
  • Zoom
  • Virtual Slides
  • speed parameter will have no effect
  • All transition start/end related events (use slideChange instead)
  • slidesPerGroup has limited support
  • centeredSlides is not supported
  • Changing slides with with anything except touch/swipe and mousewheel will happen without transition in browsers without scrollTo.behaviour = 'smooth' support (e.g. in desktop and iOS Safari)
  • simulateTouch doesn't have effect and "dragging" with mouse doesn't work
  • resistance doesn't have any effect
  • allowSlidePrev/Next
  • swipeHandler
  • freeMode and all relevant features
Slides grid
spaceBetweennumber0

Distance between slides in px.

If you use "margin" css property to the elements which go into Swiper in which you pass "spaceBetween" into, navigation might not work property.

slidesPerViewnumber 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

slidesPerColumnnumber1Number of slides per column, for multirow layout

slidesPerColumn > 1 is currently not compatible with loop mode (loop: true)

slidesPerColumnFillstring'column'Could be 'column' or 'row'. Defines how slides should fill rows, by column or by row. When 'column' it uses `flex-direction: column` layout which requires specified height on swiper-container.
slidesPerGroupnumber1Set numbers of slides to define and enable group sliding. Useful to use with slidesPerView > 1
slidesPerGroupSkipnumber0The 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 or greater than 1 the first X slides are treated as single groups, whereas all following slides are grouped by the slidesPerGroup value.

centeredSlidesbooleanfalseIf true, then active slide will be centered, not always on the left side.
centeredSlidesBoundsbooleanfalseIf true, then active slide will be centered without adding gaps at the beginning and end of slider. Required centeredSlides: true. Not intended to be used with loop or pagination
slidesOffsetBeforenumber0Add (in px) additional slide offset in the beginning of the container (before all slides)
slidesOffsetAfternumber0Add (in px) additional slide offset in the end of the container (after all slides)
normalizeSlideIndexbooleantrueNormalize slide index. See #1766
centerInsufficientSlidesbooleanfalseWhen enabled it center slides if the amount of slides less than `slidesPerView`. Not intended to be used loop mode and slidesPerColumn
Grab Cursor
grabCursorbooleanfalseThis option may a little improve desktop usability. If true, user will see the "grab" cursor when hover on Swiper
Touches
touchEventsTargetstring'wrapper'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)
touchRationumber1Touch ratio
touchAnglenumber45Allowable angle (in degrees) to trigger touch move
simulateTouchbooleantrueIf true, Swiper will accept mouse events like touch events (click and drag to change slides)
shortSwipesbooleantrueSet to false if you want to disable short swipes
longSwipesbooleantrueSet to false if you want to disable long swipes
longSwipesRationumber0.5Ratio to trigger swipe to next/previous slide during long swipes
longSwipesMsnumber300Minimal duration (in ms) to trigger swipe to next/previous slide during long swipes
followFingerbooleantrueIf disabled, then slider will be animated only when you release it, it will not move while you hold your finger on it
allowTouchMovebooleantrueIf false, then the only way to switch the slide is use of external API functions like slidePrev or slideNext
thresholdnumber0Threshold value in px. If "touch distance" will be lower than this value then swiper will not move
touchStartPreventDefaultbooleantrueIf disabled, `touchstart` (`mousedown`) event won't be prevented
touchStartForcePreventDefaultbooleanfalseForce to always prevent default for `touchstart` (`mousedown`) event
touchMoveStopPropagationbooleanfalseIf enabled, then propagation of "touchmove" will be stopped
iOSEdgeSwipeDetectionbooleanfalseEnable to release Swiper events for swipe-to-go-back work in iOS UIWebView
iOSEdgeSwipeThresholdnumber20Area (in px) from left edge of the screen to release touch events for swipe-to-go-back in iOS UIWebView
touchReleaseOnEdgesbooleanfalseEnable to release touch events on slider edge position (beginning, end) to allow for further page scrolling
passiveListenersbooleantruePassive 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
resistancebooleantrueSet to false if you want to disable resistant bounds
resistanceRationumber0.85This option allows you to control resistance ratio
Swiping / No swiping
preventInteractionOnTransitionbooleanfalseWhen enabled it won't allow to change slides by swiping or navigation/pagination buttons during transition
allowSlidePrevbooleantrueSet to false to disable swiping to previous slide direction (to left or top)
allowSlideNextbooleantrueSet to false to disable swiping to next slide direction (to right or bottom)
noSwipingbooleantrueEnable/disable swiping on elements matched to class specified in noSwipingClass
noSwipingClassstring'swiper-no-swiping'Specify noSwiping's' element css class
noSwipingSelectorstringCan be used instead of noSwipingClass to specify elements to disable swiping on. For example 'input' will disable swiping on all inputs
swipeHandlerstring / HTMLElementnullString with CSS selector or HTML element of the container with pagination that will work as only available handler for swiping
Clicks
preventClicksbooleantrueSet to true to prevent accidental unwanted clicks on links during swiping
preventClicksPropagationbooleantrueSet to true to stop clicks event propagation on links during swiping
slideToClickedSlidebooleanfalseSet to true and click on any slide will produce transition to this slide
Freemode
freeModebooleanfalseIf true then slides will not have fixed positions
freeModeMomentumbooleantrueIf true, then slide will keep moving for a while after you release it
freeModeMomentumRationumber1Higher value produces larger momentum distance after you release slider
freeModeMomentumVelocityRationumber1Higher value produces larger momentum velocity after you release slider
freeModeMomentumBouncebooleantrueSet to false if you want to disable momentum bounce in free mode
freeModeMomentumBounceRationumber1Higher value produces larger momentum bounce effect
freeModeMinimumVelocitynumber0.02Minimum touchmove-velocity required to trigger free mode momentum
freeModeStickybooleanfalseSet to true to enable snap to slides positions in free mode
Progress
watchSlidesProgressbooleanfalseEnable this feature to calculate each slides progress
watchSlidesVisibilitybooleanfalsewatchSlidesProgress should be enabled. Enable this option and slides that are in viewport will have additional visible class
Images
preloadImagesbooleantrueWhen enabled Swiper will force to load all images
updateOnImagesReadybooleantrueWhen enabled Swiper will be reinitialized after all inner images (<img> tags) are loaded. Required preloadImages: true
Loop
loopbooleanfalse

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
loopAdditionalSlidesnumber0Addition number of slides that will be cloned after creating of loop
loopedSlidesnumbernullIf you use slidesPerView:'auto' with loop mode you should tell to Swiper how many slides it should loop (duplicate) using this parameter
loopFillGroupWithBlankbooleanfalseEnable and loop mode will fill groups with insufficient number of slides with blank slides. Good to be used with slidesPerGroup parameter
Breakpoints
breakpointsobject

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, slidesPerColumn. Such parameters like loop and effect won't work. For example:

var swiper = new Swiper('.swiper-container', {
  // 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
    }
  }
})

Since version 5.3.0 it also supports "ratio" (width/height) breakpoints:

var swiper = new Swiper('.swiper-container', {
  slidesPerView: 1,
  spaceBetween: 10,
  breakpoints: {
    '@0.75': {
      slidesPerView: 2,
      spaceBetween: 20,
    },
    '@1.00': {
      slidesPerView: 3,
      spaceBetween: 40,
    },
    '@1.50': {
      slidesPerView: 4,
      spaceBetween: 50,
    },
  }
});
Observer
observerbooleanfalseSet 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)
observeParentsbooleanfalseSet to true if you also need to watch Mutations for Swiper parent elements
observeSlideChildrenbooleanfalseSet to true if you also need to watch Mutations for Swiper slide children elements
Namespace
containerModifierClassstring'swiper-container-'The beginning of the modifier CSS class that can be added to swiper container depending on different parameters
slideClassstring'swiper-slide'CSS class name of slide
slideActiveClassstring'swiper-slide-active'CSS class name of currently active slide
slideDuplicateActiveClassstring'swiper-slide-duplicate-active'CSS class name of duplicated slide which represents the currently active slide
slideVisibleClassstring'swiper-slide-visible'CSS class name of currently visible slide
slideDuplicateClassstring'swiper-slide-duplicate'CSS class name of slide duplicated by loop mode
slideNextClassstring'swiper-slide-next'CSS class name of slide which is right after currently active slide
slideDuplicateNextClassstring'swiper-slide-duplicate-next'CSS class name of duplicated slide which represents the slide next to active slide
slidePrevClassstring'swiper-slide-prev'CSS class name of slide which is right before currently active slide
slideDuplicatePrevClassstring'swiper-slide-duplicate-prev'CSS class name of duplicated slide which represents the slide previous to active slide
wrapperClassstring'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.paramsObject with passed initialization parameters
mySwiper.$elDom7 element with slider container HTML element. To get vanilla HTMLElement use mySwiper.el
mySwiper.$wrapperElDom7 element with slider wrapper HTML element. To get vanilla HTMLElement use mySwiper.wrapperEl
mySwiper.slidesDom7 array-like collection of slides HTML elements. To get specific slide HTMLElement use mySwiper.slides[1]
mySwiper.widthWidth of container
mySwiper.heightHeight of container
mySwiper.translateCurrent value of wrapper translate
mySwiper.progressCurrent 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.previousIndexIndex number of previously active slide
mySwiper.isBeginningtrue if slider on most "left"/"top" position
mySwiper.isEndtrue if slider on most "right"/"bottom" position
mySwiper.animatingtrue if swiper is in transition
mySwiper.touchesObject with the following touch event properties:
  • mySwiper.touches.startX
  • mySwiper.touches.startY
  • mySwiper.touches.currentX
  • mySwiper.touches.currentY
  • mySwiper.touches.diff
mySwiper.clickedIndexIndex number of last clicked slide
mySwiper.clickedSlideLink to last clicked slide (HTMLElement)
mySwiper.allowSlideNextDisable / enable ability to slide to the next slides by assigning false/true to this property
mySwiper.allowSlidePrevDisable / enable ability to slide to the previous slides by assigning false/true to this property
mySwiper.allowTouchMoveDisable / 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.slideToLoop(index, speed, runCallbacks);Does the same as .slideTo but for the case when used with enabled loop. So this method will slide to slides with realIndex matching to passed index
  • index - number - index number of original 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.slideReset(speed, runCallbacks);Reset swiper position to currently active slide for the duration equal to 'speed' parameter.
  • 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.slideToClosest(speed, runCallbacks);Reset swiper position to closest slide/snap point for the duration equal to 'speed' parameter.
  • 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.updateAutoHeight(speed);Force swiper to update its height (when autoHeight enabled) for the duration eqaul to 'speed' parameter
  • 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.changeDirection(direction);

Changes slider direction from horizontal to vertical and back.

  • direction - string - new direction, e.g. horizontal or vertical. Optional. If not specified, then will automatically changed to opposite direction
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.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:
mySwiper.addSlide(1, '<div class="swiper-slide">Slide 10"</div>')
mySwiper.addSlide(1, [
   '<div class="swiper-slide">Slide 10"</div>',
   '<div class="swiper-slide">Slide 11"</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.translateTo(translate, speed, runCallbacks, translateBounds);Animate custom css3 transform's translate value for swiper wrapper
  • translate - number - translate value (in px).
  • speed - number - transition duration (in ms).
  • runCallbacks - boolean - Set it to false (by default it is true) and transition will not produce transition events. Optional
  • translateBounds - boolean - Set it to false (by default it is true) and transition value can extend beyond min and max translate. Optional
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.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 nameArgumentsDescription
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 */
    },
  }
});
beforeDestroyEvent will be fired right before Swiper destroyed
slideChangeEvent will be fired when currently active slide is changed
slideChangeTransitionStartEvent will be fired in the beginning of animation to other slide (next or previous).
slideChangeTransitionEndEvent will be fired after animation to other slide (next or previous).
slideNextTransitionStartSame as "slideChangeTransitionStart" but for "forward" direction only
slideNextTransitionEndSame as "slideChangeTransitionEnd" but for "forward" direction only
slidePrevTransitionStartSame as "slideChangeTransitionStart" but for "backward" direction only
slidePrevTransitionEndSame as "slideChangeTransitionEnd" but for "backward" direction only
transitionStartEvent will be fired in the beginning of transition.
transitionEndEvent will be fired after transition.
touchStarteventEvent will be fired when user touch Swiper. Receives 'touchstart' event as an arguments.
touchMove(event)eventEvent will be fired when user touch and move finger over Swiper. Receives 'touchmove' event as an arguments.
touchMoveOppositeeventEvent will be fired when user touch and move finger over Swiper in direction opposite to direction parameter. Receives 'touchmove' event as an arguments.
sliderMoveeventEvent will be fired when user touch and move finger over Swiper and move it. Receives 'touchmove' event as an arguments.
touchEndeventEvent will be fired when user release Swiper. Receives 'touchend' event as an arguments.
clickeventEvent will be fired when user click/tap on Swiper. Receives 'touchend' event as an arguments.
tapeventEvent will be fired when user click/tap on Swiper. Receives 'touchend' event as an arguments.
doubleTapeventEvent will be fired when user double tap on Swiper's container. Receives 'touchend' event as an arguments
imagesReadyEvent will be fired right after all inner images are loaded. updateOnImagesReady should be also enabled
progressprogressEvent will be fired when Swiper progress is changed, as an arguments it receives progress that is always from 0 to 1
reachBeginningEvent will be fired when Swiper reach its beginning (initial position)
reachEndEvent will be fired when Swiper reach last slide
fromEdgeEvent will be fired when Swiper goes from beginning or end position
setTranslatetranslateEvent will be fired when swiper's wrapper change its position. Receives current translate value as an arguments
setTransitiontransitionEvent will be fired everytime when swiper starts animation. Receives current transition duration (in ms) as an arguments
resizeEvent will be fired on window resize right before swiper's onresize manipulation
observerUpdateEvent will be fired if observer is enabled and it detects DOM mutations
beforeLoopFixEvent will be fired right before "loop fix"
loopFixEvent will be fired after "loop fix"

Components

Improve this Doc
ParameterTypeDefaultDescription
navigationobject

Object with navigation parameters. For example:

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

{
nextElstring / HTMLElementnullString with CSS selector or HTML element of the element that will work like "next" button after click on it
prevElstring / HTMLElementnullString with CSS selector or HTML element of the element that will work like "prev" button after click on it
hideOnClickbooleanfalseToggle navigation buttons visibility after click on Slider's container
disabledClassstring'swiper-button-disabled'CSS class name added to navigation button when it becomes disabled
hiddenClassstring'swiper-button-hidden'CSS class name added to navigation button when it becomes hidden
}
Properties
mySwiper.navigation.nextElHTMLElement of "next" navigation button
mySwiper.navigation.prevElHTMLElement of "previous" navigation button
Methods
mySwiper.navigation.update();Update navigation buttons state (enabled/disabled)
Event nameArgumentsDescription
navigationHideEvent will be fired on navigation hide
navigationShowEvent will be fired on navigation show

Pagination

Improve this Doc

Pagination Parameters

ParameterTypeDefaultDescription
paginationobject

Object with navigation parameters. For example:

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

{
elstringnullString with CSS selector or HTML element of the container with pagination
typestring'bullets'String with type of pagination. Can be "bullets", "fraction", "progressbar" or "custom"
bulletElementstring'span'Defines which HTML tag will be use to represent single pagination bullet. Only for bullets pagination type.
dynamicBulletsbooleanfalseGood to enable if you use bullets pagination with a lot of slides. So it will keep only few bullets visible at the same time.
dynamicMainBulletsnumber1The number of main bullets visible when dynamicBullets enabled.
hideOnClickbooleantrueToggle (hide/true) pagination container visibility after click on Slider's container
clickablebooleanfalseIf true then clicking on pagination button will cause transition to appropriate slide. Only for bullets pagination type
progressbarOppositebooleanfalseMakes pagination progressbar opposite to Swiper's `direction` parameter, means vertical progressbar for horizontal swiper direction and horizontal progressbar for vertical swiper direction
formatFractionCurrentfunction(number)number => numberCustom format fraction pagination current number. Function receives current number, and you need to return formatted value
formatFractionTotalfunction(number)number => numberCustom format fraction pagination total number. Function receives total number, and you need to return formatted value
renderBulletfunction(index, className)nullThis 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>';
  }
});
renderFractionfunction(currentClass, totalClass)nullThis 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>';
  }
});
renderProgressbarfunction(progressbarFillClass)nullThis 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>';
  }
});
renderCustomfunction(swiper, current, total)nullThis 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;
  }
});
bulletClassstring'swiper-pagination-bullet'CSS class name of single pagination bullet
bulletActiveClassstring'swiper-pagination-bullet-active'CSS class name of currently active pagination bullet
modifierClassstring'swiper-pagination-'The beginning of the modifier CSS class name that will be added to pagination depending on parameters
currentClassstring'swiper-pagination-current'CSS class name of the element with currently active index in "fraction" pagination
totalClassstring'swiper-pagination-total'CSS class name of the element with total number of "snaps" in "fraction" pagination
hiddenClassstring'swiper-pagination-hidden'CSS class name of pagination when it becomes inactive
progressbarFillClassstring'swiper-pagination-progressbar-fill'CSS class name of pagination progressbar fill element
clickableClassstring'swiper-pagination-clickable'CSS class name set to pagination when it is clickable
lockClassstring'swiper-pagination-lock'CSS class name set to pagination when it is disabled
}

Pagination Methods & Properties

Properties
mySwiper.pagination.elHTMLElement of pagination container element
mySwiper.pagination.bulletsDom7 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)

Pagination Events

Event nameArgumentsDescription
paginationRenderswiper, paginationElEvent will be fired after pagination rendered
paginationUpdateswiper, paginationElEvent will be fired when pagination updated
paginationHideEvent will be fired on pagination hide
paginationShowEvent will be fired on pagination show

Scrollbar

Improve this Doc

Scrollbar Parameters

ParameterTypeDefaultDescription
scrollbarobject

Object with scrollbar parameters. For example:

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

{
elstring / HTMLElementnullString with CSS selector or HTML element of the container with scrollbar.
hidebooleantrueHide scrollbar automatically after user interaction
draggablebooleanfalseSet to true to enable make scrollbar draggable that allows you to control slider position
snapOnReleasebooleantrueSet to false to unsnap slider position to slides when you release scrollbar
dragSizestring/number'auto'Size of scrollbar draggable element in px
lockClassstring'swiper-scrollbar-lock'Scrollbar element additional CSS class when it is disabled
dragClassstring'swiper-scrollbar-drag'Scrollbar draggable element CSS class
}

Scrollbar Methods & Properties

Properties
mySwiper.scrollbar.elHTMLElement of Scrollbar container element
mySwiper.scrollbar.dragElHTMLElement of Scrollbar draggable handler element
Methods
mySwiper.scrollbar.updateSize();Updates scrollbar track and handler sizes

Autoplay

Improve this Doc

Autoplay Parameters

ParameterTypeDefaultDescription
autoplayobject/boolean

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

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

{
delaynumber3000

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">
stopOnLastSlidebooleanfalseEnable this parameter and autoplay will be stopped when it reaches last slide (has no effect in loop mode)
disableOnInteractionbooleantrueSet to false and autoplay will not be disabled after user interactions (swipes), it will be restarted every time after interaction
reverseDirectionbooleanfalseEnables autoplay in reverse direction
waitForTransitionbooleantrueWhen 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
}

Autoplay Methods & Properties

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

Autoplay Events

Event nameArgumentsDescription
autoplayStartEvent will be fired in when autoplay started
autoplayStopEvent will be fired when autoplay stopped
autoplayEvent will be fired when slide changed with autoplay

Parallax

Improve this Doc

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(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>

Parallax Parameters

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

Lazy Loading

Improve this Doc

To enable lazy loading, first of all we need a special layout for images or elements with background 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

ParameterTypeDefaultDescription
lazyobject/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,
  },
});

{
loadPrevNextbooleanfalseSet to "true" to enable lazy loading for the closest slides images (for previous and next slide images)
loadPrevNextAmountnumber1Amount of next/prev slides to preload lazy images in. Can't be less than slidesPerView
loadOnTransitionStartbooleanfalseBy 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
elementClassstring'swiper-lazy'CSS class name of lazy element
loadingClassstring'swiper-lazy-loading'CSS class name of lazy loading element
loadedClassstring'swiper-lazy-loaded'CSS class name of lazy loaded element
preloaderClassstring'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 nameArgumentsDescription
lazyImageLoadslideEl, imageElEvent will be fired in the beginning of lazy loading of image
lazyImageReadyslideEl, imageElEvent will be fired when lazy loading image will be loaded

Fade Effect

Improve this Doc

Fade Effect Parameters

Be sure to have the `effect` param set to `fade` in order for this to work.

ParameterTypeDefaultDescription
fadeEffectobject

Object with Fade-effect parameters. For example:

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

{
crossFadebooleanfalseEnables slides cross fade
}

Coverflow Effect

Improve this Doc

Coverflow Effect Parameters

Be sure to have the `effect` param set to `coverflow` in order for this to work.

ParameterTypeDefaultDescription
coverflowEffectobject

Object with Coverflow-effect parameters. For example:

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

{
slideShadowsbooleantrueEnables slides shadows
rotatenumber50Slide rotate in degrees
stretchnumber0Stretch space between slides (in px)
depthnumber100Depth offset in px (slides translate in Z axis)
modifiernumber1Effect multipler
}

Flip Effect

Improve this Doc

Flip Effect Parameters

Be sure to have the `effect` param set to `flip` in order for this to work.

ParameterTypeDefaultDescription
flipEffectobject

Object with Flip-effect parameters. For example:

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

{
slideShadowsbooleantrueEnables slides shadows
limitRotationbooleantrueLimit edge slides rotation
}

Cube Effect

Improve this Doc

Cube Effect Parameters

Be sure to have the `effect` param set to `cube` in order for this to work.

ParameterTypeDefaultDescription
cubeEffectobject

Object with Cube-effect parameters. For example:

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

{
slideShadowsbooleantrueEnables slides shadows
shadowbooleantrueEnables main slider shadow
shadowOffsetnumber20Main shadow offset in px
shadowScalenumber0.94Main shadow scale ratio
}

Thumbs

Improve this Doc

In addition to Controller component Swiper comes with Thumbs component that is designed to work with additional thumbs swiper in a more correct way than Controller which is used for syncing two swipers.

Thumbs Parameters

ParameterTypeDefaultDescription
thumbsobject

Object with thumbs component parameters. For example:

var mySwiper = new Swiper('.swiper-container', {
  ...
  thumbs: {
    swiper: thumbsSwiper
  }
});

{
swiperobject
Swiper
Swiper instance of swiper used as thumbs or object with Swiper parameters to initialize thumbs swiper. For example:
var thumbsSwiper = new Swiper('.swiper-container-thumbs', {
  slidesPerView: 5,
});

var mySwiper = new Swiper('.swiper-container', {
  ...
  thumbs: {
    swiper: thumbsSwiper
  }
});

or

var mySwiper = new Swiper('.swiper-container', {
  ...
  thumbs: {
    swiper: {
      el: '.swiper-container-thumbs',
      slidesPerView: 5,
      ...
    }
  }
});
slideThumbActiveClassstring'swiper-slide-thumb-active'Additional class that will be added to activated thumbs swiper slide
thumbsContainerClassstring'swiper-container-thumbs'Additional class that will be added to thumbs swiper-container
multipleActiveThumbsbooleantrueWhen enabled multiple thumbnail slides may get activated
autoScrollOffsetnumber0Allows to set on which thumbs active slide from edge it should automaticall move scroll thumbs. For example, if set to 1 and last visible thumb will be activated (1 from edge) it will auto scroll thumbs
}

Thumbs Methods & Properties

Properties
mySwiper.thumbs.swiperSwiper instance of thumbs swiper

Zoom

Improve this Doc

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-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>

Zoom Parameters

ParameterTypeDefaultDescription
zoomobject/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,
  },
});

{
maxRationumber3Maximum image zoom multiplier
minRationumber1Minimal image zoom multiplier
togglebooleantrueEnable/disable zoom-in by slide's double tap
containerClassstring'swiper-zoom-container'CSS class name of zoom container
zoomedSlideClassstring'swiper-slide-zoomed'CSS class name of zoomed in container
}

Zoom Methods & Properties

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

Zoom Events

Event nameArgumentsDescription
zoomChangescale, imageEl, slideElEvent will be fired when zoom changes

Keyboard Control

Improve this Doc

Keyboard Control Parameters

ParameterTypeDefaultDescription
keyboardobject/booleanfalse

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

var mySwiper = new Swiper('.swiper-container', {
  keyboard: {
    enabled: true,
    onlyInViewport: false,
  },
});

{
enabledbooleanfalseSet to true to enable keyboard control
onlyInViewportbooleantrueWhen enabled it will control sliders that are currently in viewport
pageUpDownbooleantrueWhen enabled it will enable keyboard navigation by Page Up and Page Down keys
}

Keyboard Methods & Properties

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

Mousewheel Control

Improve this Doc

Mousewheel Control Parameters

ParameterTypeDefaultDescription
mousewheelobject/booleanfalse

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,
  },
});

{
forceToAxisbooleanfalseSet 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.
releaseOnEdgesbooleanfalseSet 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)
invertbooleanfalseSet to true to invert sliding direction
sensitivitynumber1Multiplier of mousewheel data, allows to tweak mouse wheel sensitivity
eventsTargetstring / 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.enabledWhether the mousewheel control is enabled
Methods
mySwiper.mousewheel.enable();Enable mousewheel control
mySwiper.mousewheel.disable();Disable mousewheel control

Virtual Slides

Improve this Doc

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

Virtual Slides Parameters

ParameterTypeDefaultDescription
virtualobject/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'],
  },
});

{
slidesarray[]Array with slides
cachebooleantrueEnables DOM cache of rendering slides html elements. Once they are rendered they will be saved to cache and reused from it.
renderSlidefunction(slide, index)nullFunction 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.
renderExternalfunction(data)nullFunction 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
addSlidesBeforenumber0Increases amount of pre-rendered slides before active slide
addSlidesAfternumber0Increases amount of pre-rendered slides after active slide
}

Virtual Slides Methods & Properties

Properties
mySwiper.virtual.cacheObject with cached slides HTML elements
mySwiper.virtual.fromIndex of first rendered slide
mySwiper.virtual.toIndex of last rendered slide
mySwiper.virtual.slidesArray with slide items passed by virtual.slides parameter
Methods
mySwiper.virtual.appendSlide(slides);Append slide. slides can be a single slide item or array with such slides.
mySwiper.virtual.prependSlide(slides);Prepend slide. slides can be a single slide item or array with such slides.
mySwiper.virtual.removeSlide(slideIndexes);Remove specific slide or slides. slideIndexes can be a number with slide index to remove or array with indexes.
mySwiper.virtual.removeAllSlides();Remove all slides.
mySwiper.virtual.update();Update virutal slides state.

renderExternal Example

renderExternal allows to bypass slides rendering to other libraries, and can be super handy with libraries like React.js and Vue.js

With Vue.js

<template>
  <!-- ... -->
  <div class="swiper-container">
    <div class="swiper-wrapper">
      <!-- It is important to set "left" style prop on every slide -->
      <div class="swiper-slide"
        v-for="(slide, index) in virtualData.slides"
        :key="index"
        :style="{left: `${virtualData.offset}px`}"
      >{{slide}}</div>
    </div>
  </div>
  <!-- ... -->
</template>
<script>
  import Swiper from 'swiper/js/swiper.esm.bundle';

  export default {
    data() {
      return {
        // dummy slides data
        slides: (function () {
          var slides = [];
          for (var i = 0; i < 600; i += 1) {
            slides.push('Slide ' + (i + 1));
          }
          return slides;
        }()),
        // virtual data
        virtualData: {
          slides: [],
        },
      }
    },
    mounted() {
      const self = this;
      const swiper = new Swiper('.swiper-container', {
        // ...
        virtual: {
          slides: self.slides,
          renderExternal(data) {
            // assign virtual slides data
            self.virtualData = data;
          },
        },
      });
    },
  };
</script>

With React.js

import React from 'react';
import Swiper from 'swiper/js/swiper.esm.bundle';

export default class extends React.Component {
  constructor() {
    this.state = {
      // dummy slides data
      slides: (function () {
        var slides = [];
        for (var i = 0; i < 600; i += 1) {
          slides.push('Slide ' + (i + 1));
        }
        return slides;
      }()),
      // virtual data
      virtualData: {
        slides: [],
      },
    }
  }
  componentDidMount() {
    const self = this;
    const swiper = new Swiper('.swiper-container', {
      // ...
      virtual: {
        slides: self.state.slides,
        renderExternal(data) {
          // assign virtual slides data
          self.setState({
            virtualData: data,
          });
        }
      },
    });
  }
  render() {
    {/* ... */}
    <div className="swiper-container">
      <div className="swiper-wrapper">
        {/* It is important to set "left" style prop on every slide */}
        {this.state.virtualData.slides.map((slide, index) => (
          <div className="swiper-slide"
            key={index}
            style={{left: `${virtualData.offset}px`}}
          >{slide}</div>
        ))}
      </div>
    </div>
    {/* ... */}
  }
}

Hash Navigation

Improve this Doc

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

ParameterTypeDefaultDescription
hashNavigationobject/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,
  },
});

{
watchStatebooleanfalseSet to true to enable also navigation through slides (when hashnav is enabled) by browser history or by setting directly hash on document location
replaceStatebooleanfalseWorks in addition to hashnav to replace current url state with the new one instead of adding it to history
}

Hash Navigation Events

Event nameArgumentsDescription
hashChangeEvent will be fired on window hash change
hashSetEvent will be fired when swiper updates the hash

History Navigation

Improve this Doc

History Navigation Parameters

ParameterTypeDefaultDescription
historyobject/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>
{
replaceStatebooleanfalseWorks in addition to hashnav or history to replace current url state with the new one instead of adding it to history
keystring'slides'Url key for slides
}

Controller

Improve this Doc

Controller Parameters

ParameterTypeDefaultDescription
controllerobject/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]undefinedPass here another Swiper instance or array with Swiper instances that should be controlled by this Swiper
inversebooleanfalseSet to true and controlling will be in inverse direction
bystring'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)

Improve this Doc

Accessibility Parameters

ParameterTypeDefaultDescription
a11yobject/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',
  },
});

{
enabledbooleantrueEnables A11y
prevSlideMessagestring'Previous slide'Message for screen readers for previous button
nextSlideMessagestring'Next slide'Message for screen readers for next button
firstSlideMessagestring'This is the first slide'Message for screen readers for previous button when swiper is on first slide
lastSlideMessagestring'This is the last slide'Message for screen readers for previous button when swiper is on last slide
paginationBulletMessagestring'Go to slide {{index}}'Message for screen readers for single pagination bullet
notificationClassstring'swiper-notification'CSS class name of a11y notification
}

Custom Build

Improve this Doc

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/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 package/ folder.