javascriptswiper.js

Swiper.js loop when slidesPerView is bigger than half of the amount of Slides


As it seems since version 9 of swiper.js you cannot loop through your slides if you do not have more than double the slides available than slidesPerView. So for example if I want to build a slider that shows 5 products at once, and want to loop through a list of 7 products I cannot do that. If I show just 1 or 2 products at once everything is fine.

This behavior seems to come from the new loop logic they implemented. Here is my configuration for the swiper:

const params = 
            modules: [Autoplay, Pagination, Navigation],
            autoplay: {
                enabled: false,
                speed: 3000,
            },
            speed: 400,
            navigation: true,
            pagination:{
                enabled: true,
                dynamicBullets: true,
                dynamicMainBullets: 4
            },
            loop: true,
            spaceBetween: 30,
            centeredSlides: false,
            breakpoints: {
                0: {
                    slidesPerView: 1,
                },
                [BREAKPOINT_WIDTH.extraSmall*16]: {
                    slidesPerView: 3
                },
                [BREAKPOINT_WIDTH.medium*16]: {
                    slidesPerView: 3
                },
                [BREAKPOINT_WIDTH.large*16]: {
                    slidesPerView: 5
                }
            },
        };

Is there an option I overlooked? Or has somebody a solution for the problem?


EDIT: As of v11 of Swiperjs this is fixed and it works again.


Solution

  • Sadly, from the v9 the loop isn't working anymore, as you mention and as explained on their documentation

    Because of nature of how the loop mode works (it will rearrange slides), total number of slides must be >= slidesPerView * 2

    So sadly for now you have no option than dirty work arround.

    1. Stay on swiper v8

    2. Increase your total number of slides by duplicating the rendered item Poor solution

    if(slidesPerView * 2 < items?.length) items = items.concat(items)
    
    1. Put a limit on your slidesPerView to adapt himself to how many items you'll be rendering
    const slidesPerView = items.length >= slidesPerView * 2 ? slidesPerView : Math.floor(items.length / 2)
    

    Note: I saw that even if you respect the number, if you add autoHeight: true it wont be working properly

    Note

    I've already open an issue in the swiper.js Github repo, but this went closed as not planned, so we'll have to live with it :/