Zoom in/out slider with Swiper js
Dima Prohorenko
Posted on March 17, 2021
Today I'm gonna show you how to create simple zoom in out effect with Swiper js.
First we need to import necessary files.
Include styles in the head and script in the end of the body tag.
<link rel="stylesheet" href="https://unpkg.com/swiper/swiper-bundle.min.css" />
<script src="https://unpkg.com/swiper/swiper-bundle.min.js"></script>
Add required markup.
<div class="container"> <!-- container to center and set slider width -->
<div class="swiper-container">
<div class="swiper-wrapper">
<div class="swiper-slide">
<div class="swiper-zoom-container"> <!-- All "zoomable" images should be wrapped with the div with swiper-zoom-container class. -->
<img src="http://pngimg.com/uploads/bottle/bottle_PNG2095.png" />
</div>
</div>
<div class="swiper-slide">
<div class="swiper-zoom-container">
<img src="http://pngimg.com/uploads/bottle/bottle_PNG2093.png" />
</div>
</div>
<div class="swiper-slide">
<div class="swiper-zoom-container">
<img src="http://pngimg.com/uploads/bottle/bottle_PNG2081.png" />
</div>
</div>
</div>
</div>
</div>
Styles
body {
margin: 0;
height: 100vh;
display: flex;
align-items: center;
justify-content: center;
}
.container {
width: 600px;
height: 600px;
}
.swiper-container,
.swiper-wrapper,
.swiper-slide {
width: 100%;
height: 100%;
}
.swiper-slide img {
display: block;
margin: 0 auto;
width: auto;
height: 80%;
}
And now it's time to add JavaScript.
// Initialize new Swiper instance
const swiper = new Swiper(".swiper-container", {
// Setting default settings
grabCursor: true,
centeredSlides: true,
loop: true,
// Setting minimum and maximum zoom ration
zoom: {
maxRatio: 1.2,
minRation: 1
},
});
// Use built in zoom.in() and zoom.out() function to scale images
// When slide starts to change slideChangeTransitionStart event fires and we use it to scale down the image.
swiper.on("slideChangeTransitionStart", swiper.zoom.out);
// And when transition has finished scale it up.
swiper.on("slideChangeTransitionEnd", swiper.zoom.in);
That's it. Hope you liked it:)
💖 💪 🙅 🚩
Dima Prohorenko
Posted on March 17, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.