DEV Community

Dima Prohorenko
Dima Prohorenko

Posted on

Zoom in/out slider with Swiper js

Today I'm gonna show you how to create simple zoom in out effect with Swiper js.

Alt Text

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>


Enter fullscreen mode Exit fullscreen mode

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>


Enter fullscreen mode Exit fullscreen mode

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%;
}


Enter fullscreen mode Exit fullscreen mode

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


Enter fullscreen mode Exit fullscreen mode

That's it. Hope you liked it:)

Top comments (1)

Collapse
 
retrop5 profile image
retrop5

Loved it! Thanks