Swiper can be installed via npm, yarn, or by directly including the CSS and JS files.
npm:
npm install swiper
yarn:
yarn add swiper
CDN (for quick testing and small projects): Include the necessary CSS and JS files from the official Swiper CDN. Refer to the Swiper documentation for the most up-to-date CDN links. You’ll typically need both a CSS file (for styling) and a JS file (for functionality).
After installing Swiper, you’ll need an HTML container to hold your slides. This container will be targeted by Swiper’s JavaScript. Each slide is typically represented as a child element within this container (e.g., <div>
elements). Swiper’s JavaScript then initializes, taking this container as a parameter. Basic configuration options can be passed to customize the Swiper instance.
Let’s create a simple Swiper instance. Assume you’ve already installed Swiper via npm or yarn.
index.html
):<!DOCTYPE html>
<html>
<head>
<title>Swiper Example</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/swiper@9/swiper-bundle.min.css"/>
</head>
<body>
<div class="swiper">
<div class="swiper-wrapper">
<div class="swiper-slide">Slide 1</div>
<div class="swiper-slide">Slide 2</div>
<div class="swiper-slide">Slide 3</div>
</div>
</div>
<script src="https://cdn.jsdelivr.net/npm/swiper@9/swiper-bundle.min.js"></script>
<script>
new Swiper('.swiper', {
// Optional parameters
;
})</script>
</body>
</html>
import Swiper from 'swiper';
). The above example uses the CDN.Remember to replace "https://cdn.jsdelivr.net/npm/swiper@9/swiper-bundle.min.css"
and "https://cdn.jsdelivr.net/npm/swiper@9/swiper-bundle.min.js"
with your actual paths if you are not using the CDN.
For npm/yarn installations, you’ll typically import Swiper into your JavaScript file and then initialize it using the appropriate selector for your Swiper container. For CDN installations, simply include the CSS and JavaScript files in your HTML <head>
and <body>
respectively, then initialize Swiper in a <script>
tag, ensuring it runs after the Swiper CSS and the HTML container are loaded. Remember to consult the Swiper documentation for the most current and accurate instructions, as specific file paths and import methods may change across Swiper versions.
A Swiper instance is a single, independently managed Swiper carousel. You create a Swiper instance by calling the Swiper
constructor, passing it a CSS selector or a DOM element that represents the container for your slider. This container must contain the slides. The constructor also accepts an options object which allows you to configure various aspects of the slider’s behavior, appearance, and interaction. Each Swiper instance manages its own state and parameters. You can have multiple Swiper instances on a single page, each operating independently.
Slides are the individual elements within a Swiper instance that are displayed sequentially. Each slide is usually represented by a <div>
element (or similar) with the class swiper-slide
. These slides are contained within a wrapper element, usually with the class swiper-wrapper
, which is itself contained within the main Swiper container. The number of slides determines the length of the Swiper carousel.
Navigation refers to the controls that allow users to manually move between slides. Swiper provides built-in support for creating navigation buttons (typically “prev” and “next” buttons). You specify the elements representing your navigation buttons in the Swiper parameters. Swiper then handles the logic to enable and disable these buttons based on the currently visible slide. Custom navigation elements can also be implemented.
Pagination provides visual indicators (often small dots or numbers) showing the current slide’s position within the carousel. Swiper can automatically create pagination elements based on the number of slides or you can provide your own custom pagination elements. The Swiper parameters specify the elements for the pagination. These parameters handle the updating of the active pagination element as the user navigates between slides.
Parameters are options you pass to the Swiper constructor to configure its behavior. These parameters control various aspects, such as the number of slides visible at once (slidesPerView
), the spacing between slides (spaceBetween
), the effect used for transitions (effect
), automatic sliding (autoplay
), navigation and pagination configurations, and many more. The complete list of parameters and their usage is documented in the Swiper API documentation. Correctly configuring these parameters is crucial to customizing the behavior of your Swiper instances.
Swiper is initialized by creating a new Swiper
instance. This is done by calling the Swiper
constructor and passing it the necessary parameters:
// Using a CSS selector:
const swiper = new Swiper('.swiper-container', {
// parameters
;
})
// Using a DOM element:
const swiperContainer = document.querySelector('.swiper-container');
const swiper = new Swiper(swiperContainer, {
// parameters
; })
The first argument is the container element (either a CSS selector string or a DOM element). The second argument is an object containing the parameters to configure the Swiper instance. See the “Parameters” section for details.
Swiper provides a rich set of methods to interact with and control the slider programmatically. Examples include:
slideNext()
: Moves to the next slide.slidePrev()
: Moves to the previous slide.slideTo(index, speed, runCallbacks)
: Moves to a specific slide. index
is the slide index (0-based), speed
is the animation speed in milliseconds, and runCallbacks
is a boolean indicating whether to trigger callbacks.slideToLoop(index, speed, runCallbacks)
: Similar to slideTo
, but handles looping in looped mode.destroy()
: Destroys the Swiper instance, removing event listeners and cleaning up resources.update()
: Updates the Swiper layout and parameters. Call this if the content or dimensions of the slider change dynamically.getSwiper()
: Returns the Swiper instance object. Useful for accessing internal properties and methods for more advanced customizations.A complete list of methods and their usage is available in the official Swiper documentation.
Swiper triggers various events throughout its lifecycle. These events allow you to respond to actions such as slide changes, transition starts and ends, and more. You can listen for these events using the on()
method:
.on('slideChange', () => {
swiperconsole.log('Slide changed!');
;
})
.on('transitionEnd', () => {
swiperconsole.log('Transition ended!');
; })
Events can also be removed using the off()
method. The full list of available events is in the Swiper documentation.
Certain Swiper parameters can be set using data attributes directly on the Swiper container element. This is helpful for simple configurations or when you want to avoid explicitly setting parameters in JavaScript. For example, data-space-between="50"
would set the spaceBetween
parameter to 50. The available data attributes and their corresponding parameters are documented in the Swiper documentation.
Swiper instances have various properties that reflect their current state and configuration. These properties can be accessed using the dot notation (e.g., swiper.params.speed
). Examples include:
swiper.params
: Contains the initial parameters passed to the constructor.swiper.activeIndex
: The index of the currently active slide.swiper.slides
: An array of DOM elements representing the slides.swiper.realIndex
: The index of the active slide, considering loops and duplicate slides.swiper.isBeginning
: A boolean indicating if the slider is at the beginning.swiper.isEnd
: A boolean indicating if the slider is at the end.Consult the official Swiper documentation for the complete list of properties and their descriptions. Note that directly manipulating some of these properties may lead to unexpected behavior and should be done with caution. Use the provided Swiper methods whenever possible for modifying the slider’s state.
Swiper offers built-in support for “Next” and “Previous” buttons to navigate through slides. To enable this, you need to specify the selectors for your button elements in the Swiper parameters using the navigation
option. This option should be an object containing nextEl
and prevEl
properties, each holding the CSS selector for the respective button. Swiper will then automatically handle the enabling/disabling of these buttons based on the current slide position.
const swiper = new Swiper('.swiper', {
navigation: {
nextEl: '.swiper-button-next',
prevEl: '.swiper-button-prev',
,
}; })
Remember to include the buttons in your HTML, typically with classes matching the selectors above.
Navigation arrows are a visual representation of the next/previous buttons, typically displayed as arrows pointing left and right. While not distinctly separate from the next/previous buttons, customizing their appearance is often discussed as a distinct topic. You can customize their styling by using CSS on the elements you’ve specified in the navigation
parameter.
Swiper supports keyboard navigation by default. Users can use the left and right arrow keys to navigate between slides. This functionality is automatically enabled and doesn’t require any additional configuration. To disable keyboard navigation, set the keyboard
parameter to false
.
const swiper = new Swiper('.swiper', {
keyboard: false, // Disables keyboard navigation
; })
If the default navigation buttons don’t fit your design, you can create fully custom navigation. This involves creating your own HTML elements for navigation and then using Swiper’s methods (slideNext()
, slidePrev()
, slideTo()
) to update the slider when these custom elements are interacted with (e.g., by adding click event listeners).
A progress bar visually indicates the current progress through the slides. To add a progress bar, you need to specify the selector for your progress bar element in the Swiper parameters using the scrollbar
option. This option should be an object which defines the el
property containing the CSS selector for your progress bar element. Swiper will then automatically update the progress bar’s fill based on the current slide.
const swiper = new Swiper('.swiper', {
scrollbar: {
el: '.swiper-scrollbar',
,
}; })
Remember to include the progress bar element in your HTML, typically with a class matching the selector above. Swiper will style this element by default, but you can customize its appearance using CSS.
Swiper offers several types of pagination, selectable through parameters. The most common types are:
Bullet Pagination: This is the default pagination type. It displays a series of small dots or bullets, one for each slide. The active bullet visually indicates the current slide.
Fraction Pagination: This type displays the current slide number as a fraction (e.g., “1/5”).
Progress Pagination: This displays a progress bar that fills as the user moves through the slides.
While Swiper provides built-in pagination types, you can create fully custom pagination. This involves creating your own HTML elements for pagination and then using Swiper’s events and methods to update them according to the current slide. You would listen to the slideChange
event and update your custom pagination elements accordingly. For example, you might change the class or text content of elements to reflect the active slide.
Fraction pagination shows the current slide number as a fraction (e.g., “1/10”). To enable fraction pagination, set the pagination.type
parameter to 'fraction'
. You’ll also need to specify the element to render the pagination using pagination.el
.
const swiper = new Swiper('.swiper', {
pagination: {
el: '.swiper-pagination',
type: 'fraction',
,
}; })
Remember to include the swiper-pagination
element in your HTML.
Progress pagination displays a progress bar reflecting the user’s progress through the slides. Enable it by setting pagination.type
to 'progressbar'
. Similar to fraction pagination, you need to specify the pagination.el
parameter to point to your progress bar element.
const swiper = new Swiper('.swiper', {
pagination: {
el: '.swiper-pagination',
type: 'progressbar',
,
}; })
The progress bar’s appearance can be customized using CSS.
Regardless of the pagination type (bullet, fraction, progress, or custom), you can customize its appearance using CSS. Swiper applies default styles, but you have full control over styling aspects such as color, size, spacing, and other visual properties by targeting the relevant CSS classes applied to the pagination elements. You can also add or remove classes dynamically based on your application’s needs. Refer to the Swiper documentation for details on the CSS classes applied to pagination elements.
Swiper supports various transition effects between slides, enhancing the visual appeal of your carousels. These effects are controlled using the effect
parameter in the Swiper initialization options.
The Cube effect creates a 3D cube-like transition. Slides rotate around a central axis to reveal the next slide. To enable the Cube effect:
const swiper = new Swiper('.swiper', {
effect: 'cube',
; })
Additional parameters within the cubeEffect
object (within the effect
parameter) allow you to fine-tune aspects like the shadow, slide size, and cube’s rotation axis. See the Swiper documentation for detailed options.
The Coverflow effect simulates a cover flow, similar to what’s seen in Apple’s Cover Flow interface. Slides appear to be fanned out in 3D space.
const swiper = new Swiper('.swiper', {
effect: 'coverflow',
; })
The coverflowEffect
object allows you to customize properties such as the rotate, stretch, depth, and modifier.
The Fade effect simply fades the current slide out while fading the next slide in. It’s a simple yet effective transition for clean transitions.
const swiper = new Swiper('.swiper', {
effect: 'fade',
; })
The fadeEffect
object provides options for controlling the crossFade parameter.
The Flip effect creates a card-flipping animation. Slides appear to flip over to reveal the next slide.
const swiper = new Swiper('.swiper', {
effect: 'flip',
; })
The flipEffect
object allows you to control the limitRotation, and set whether to flip from the ‘left’ or ‘right’ using the flipEffect.flipDirection
property.
Swiper also includes several creative effects that provide more visually striking transitions. These can be more complex and may require additional configuration. The specific options and possibilities vary depending on the chosen creative effect. Consult the Swiper documentation for detailed information on available creative effects and their parameters.
For advanced users, Swiper allows creating custom transition effects. This involves implementing custom JavaScript code that interacts with Swiper’s internal APIs to control the animation of slides. This approach is significantly more advanced and necessitates a solid understanding of Swiper’s architecture and animation principles. It typically requires manipulating CSS transforms directly. Consult the Swiper documentation for guidance on creating custom effects, as this is a significantly more involved task.
Lazy loading improves performance by loading slide content only when it’s needed. Swiper’s lazy loading functionality allows you to defer loading of images or other resources until the slide is about to become visible. Enable it by setting the lazy
parameter to true
and optionally providing selectors to target lazy load images (e.g., lazy: {loadPrevNext: true, loadPrevNextAmount: 1}
. The loadPrevNext
option loads images in nearby slides and loadPrevNextAmount
defines how many slides to preload. Ensure your images have the data-src
attribute specifying the actual image URL.
Virtual slides optimize performance when dealing with a large number of slides. Instead of rendering all slides at once, Swiper renders only a limited number of slides around the currently active slide. You’ll need to configure the virtual
parameter, providing the total number of slides (slidesnumber
) and optionally a renderSlide
callback function which can further customize how virtual slides are rendered.
Autoplay automatically transitions between slides at a specified interval. Enable it by setting the autoplay
parameter to true
and optionally configure the delay (in milliseconds) and other options like disableOnInteraction
(pauses on user interaction).
const swiper = new Swiper('.swiper', {
autoplay: {
delay: 3000,
disableOnInteraction: false, // Keep autoplay running even after interaction
,
}; })
Loop mode allows continuous looping through slides. The last slide transitions seamlessly back to the first, creating an infinite loop. Enable it by setting loop: true
. Note that using loop mode requires some careful consideration of slide structure and may require duplicated slides.
Hash navigation allows linking to specific slides using URL hashes. Enable it using the hashNavigation
parameter. This will automatically update the URL hash based on the current slide, and clicking a link with the corresponding hash will navigate to that slide.
Swiper provides keyboard navigation by default (left/right arrows). You can disable this using keyboard: false
. For more fine-grained control, you can specify which keys trigger navigation using the keyboard.onlyInViewport
or keyboard.pageUpDown
options.
Building accessible Swipers requires careful attention to ARIA attributes and keyboard navigation. Ensure that the swiper-slide
elements have appropriate ARIA roles (like role="group"
for the wrapper and role="presentation"
for individual slides), labels, and aria-current
attributes to indicate the active slide. Provide sufficient visual contrast for elements and consider providing alternative text for images. Proper keyboard navigation is essential for screen reader users, so using keyboard controls or building custom keyboard controls that respect ARIA standards is crucial. Thoroughly test your implementation with assistive technologies.
Swiper makes it easy to create responsive sliders that adapt to different screen sizes.
Breakpoints define the screen size ranges at which the slider’s behavior or appearance changes. Swiper uses these breakpoints to adjust parameters based on the current viewport width. You define breakpoints using the breakpoints
parameter, which is an object where keys represent the breakpoint width (in pixels or other units) and values are objects containing the parameters that should be applied at that breakpoint.
const swiper = new Swiper('.swiper', {
breakpoints: {
// when window width is >= 640px
640: {
slidesPerView: 2,
spaceBetween: 20,
,
}// when window width is >= 1024px
1024: {
slidesPerView: 3,
spaceBetween: 40,
,
},
}; })
In this example, the slider will display 1 slide per view on smaller screens, 2 slides per view on screens 640px or wider, and 3 slides per view on screens 1024px or wider. The spaceBetween
parameter also adjusts accordingly.
Many Swiper parameters are responsive; that is, their value can change based on the breakpoint. Any parameter that accepts a numerical value, a string value (that could be resolved as a CSS unit), or an object can potentially be responsive. For those that accept an object, the object keys become the breakpoint names, and the values are the parameter values for each breakpoint. For others, you can use the breakpoint object within the main parameter object.
Adaptive heights allow the slider’s height to automatically adjust to the height of the tallest slide at a given breakpoint. This is particularly useful when slides have varying content heights. To use this, simply set the allowSlideNext
and allowSlidePrev
options to true. If these are not set, Swiper’s height will default to the height of the first slide. The height will then adapt as users slide to taller content. You don’t need to explicitly configure adaptive heights beyond ensuring that the slider is correctly configured to allow the slide change.
Swiper offers various ways to customize its appearance and integrate it seamlessly into your project’s design.
The simplest way to customize Swiper’s appearance is by directly modifying its CSS. Swiper provides a well-structured CSS framework with specific classes for different elements (slides, navigation, pagination, etc.). You can override these styles in your own CSS file, ensuring that your changes are applied after Swiper’s default stylesheet is loaded. Remember to be mindful of the specificity of your CSS selectors to avoid unintended consequences.
For more advanced customization, Swiper provides Sass/SCSS source files. This allows you to modify the variables and mixins provided by Swiper’s Sass files to tailor the styles precisely. This approach offers greater flexibility and maintainability compared to directly editing the compiled CSS. Using a CSS preprocessor requires additional setup for compiling the Sass/SCSS files into CSS before you can use it in your project.
Swiper may offer predefined themes (check the Swiper documentation for the latest available themes). These themes provide pre-configured styles for different design aesthetics. Using a predefined theme can significantly accelerate the styling process, providing a solid starting point that you can then customize further.
You can create your own custom themes from scratch, either by modifying an existing theme or starting from a blank slate. This involves creating your own Sass/SCSS files, defining variables, mixins, and styles that conform to Swiper’s structure. You can then incorporate these styles into your project, providing a fully custom and branded Swiper implementation. The level of effort required will depend on the complexity and uniqueness of your design requirements. Ensure that your custom theme styles are loaded after Swiper’s core stylesheets to override them effectively.
This section provides guidance on resolving common issues and optimizing Swiper performance.
Swiper not initializing: Double-check that you’ve correctly included the Swiper JavaScript and CSS files (or imported them correctly via npm/yarn). Ensure the Swiper container element exists in the DOM and that the selector you’re using to target it is accurate. Inspect the browser’s developer console for JavaScript errors.
Slides not displaying correctly: Verify that your slide elements have the swiper-slide
class. Make sure the swiper-wrapper
element contains the swiper-slide
elements. Inspect the browser’s developer console for JavaScript errors related to Swiper initialization or configuration. Check for CSS conflicts that might be affecting the layout of the slider.
Navigation/pagination not working: Ensure that you’ve correctly specified the selectors for your navigation and pagination elements in the Swiper parameters. Verify that these elements exist in the DOM and are accessible to Swiper. Check the browser’s developer console for any errors.
Performance issues: For large numbers of slides or complex effects, performance can suffer. Consider implementing lazy loading and/or virtual slides to optimize performance. Minimize the use of computationally expensive effects.
CSS conflicts: Swiper’s default styles might conflict with your project’s CSS. Use browser developer tools to inspect the CSS applied to Swiper elements and identify any conflicting styles. Use more specific selectors in your custom CSS to override Swiper’s default styles without affecting other parts of your website.
Browser Developer Tools: Use your browser’s developer tools (usually accessed by pressing F12) to inspect the HTML structure, CSS styles, and JavaScript console for errors or warnings. The console will often provide helpful clues about what’s going wrong.
Swiper Documentation: The official Swiper documentation is an invaluable resource. Consult it for detailed explanations of parameters, methods, and events.
Simplify: When encountering issues, try simplifying your Swiper setup. Create a minimal example with only the essential elements and parameters to isolate the problem. Gradually add complexity back in until you identify the source of the issue.
Check for errors: Pay close attention to any JavaScript errors that appear in the browser’s developer console. These errors often pinpoint the exact location of the problem in your code.
Version Compatibility: Ensure compatibility between your Swiper version and other libraries or frameworks used in your project. Check Swiper’s release notes and documentation for compatibility information.
Lazy Loading: Implement lazy loading to defer loading of images or other resources until they are about to be visible.
Virtual Slides: Use virtual slides for large numbers of slides to improve rendering performance.
Minimize Effects: Avoid using computationally expensive effects, especially with many slides. Simple transitions (like fade) generally perform better than complex 3D effects.
Optimize Images: Optimize images to reduce their file size without significantly affecting their visual quality. Use appropriate image formats (e.g., WebP) and compression techniques.
CSS Optimization: Ensure your CSS is well-structured and avoid unnecessary styles or selectors. Minimize the use of computationally expensive CSS properties.
JavaScript Optimization: Optimize your JavaScript code to avoid unnecessary calculations or DOM manipulations. Minimize the number of event listeners and use efficient data structures.
This section guides you through upgrading to the latest version of Swiper and addresses potential compatibility issues.
Upgrading Swiper generally involves updating the included JavaScript and CSS files (or updating your package via npm or yarn). Always refer to the official release notes for the version you are upgrading to. The release notes will detail any significant changes, new features, bug fixes, and, most importantly, any breaking changes.
The general upgrade process is usually straightforward:
Update the package: If using npm or yarn, run npm update swiper
or yarn upgrade swiper
to update to the latest version.
Update CDN links: If using a CDN, replace the old CDN links with the updated links provided in the Swiper documentation.
Review breaking changes: Carefully review the release notes for breaking changes. Breaking changes often require code modifications to maintain functionality.
Test thoroughly: After updating, thoroughly test your Swiper implementation to ensure all features are working as expected. Pay close attention to areas that may have been affected by breaking changes.
Breaking changes are modifications to Swiper that may cause your existing code to stop working correctly. These changes are usually documented in the release notes for each new version. They can range from changes in parameter names or values to the removal of features or significant alterations to the API.
Before upgrading, always carefully review the release notes for the target version to identify any potential breaking changes. The release notes will typically explain the changes and suggest ways to adapt your code to the new version.
Swiper generally maintains backward compatibility, but some versions might introduce breaking changes. Always check the documentation for compatibility information. If you are using older versions of Swiper, upgrading to a newer version might require significant code changes, depending on the extent of breaking changes introduced between versions.
It’s crucial to carefully plan any upgrades and test them thoroughly to avoid unexpected issues. Consider creating a backup of your project before upgrading to ensure you can revert if necessary. When upgrading across major versions (e.g., from Swiper 7 to Swiper 9), more extensive testing and code adjustments are likely required due to a greater probability of breaking changes.
We welcome contributions to Swiper! Whether you’re reporting a bug, submitting a feature request, or contributing code, your involvement is valuable.
When reporting a bug, please provide as much detail as possible to help us reproduce and fix the issue quickly. A good bug report typically includes:
Please use the issue tracker on the Swiper repository to report bugs. Before submitting a new issue, search existing issues to see if the bug has already been reported.
Pull requests (PRs) are welcome for bug fixes, new features, and improvements to the documentation. Before submitting a PR:
fix/bug-123
or feature/new-feature
).Swiper follows specific coding standards to ensure consistency and maintainability. These standards typically include:
Before submitting a pull request, ensure your code adheres to these standards. The project maintainers may request changes if your code doesn’t meet these standards. Using a linter and formatter can greatly assist in ensuring code quality and consistency.