Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swiper - wrong width on init, correct width after resize

I am working on a project using Swiper and everythings working fine after resizing the window. But on init the width of the slides is not correct. I tried reproducing this locally but without success. I set 4 slides per View, but it's calculating the width for 3 1/2 slides. I cleared everything except slidesPerView from my configuration but no change at all. Could it be some kind of collision with other frameworks or plugins? If additional information is needed to solve this issue, just ask! :-)

EDIT

HTML:

<div id="gallery_container">
    <div id="galleryLeft"></div>
    <div id="gallery-swiper">
        <div class="swiper-wrapper">
            <div class="swiper-slide">
                ...
            </div>
        </div>
    </div>
    <div id="galleryRight"></div>
</div>

Initialisation:

(function($) {
    $(document).ready(function() {
        var gallery_swiper = new Swiper('#gallery-swiper', {
            slidesPerView: 3,
            spaceBetween: 0,
            speed: 500,
            prevButton: '#galleryLeft',
            nextButton: '#galleryRight'
        });

        var slides = gallery_swiper.slides.length;
        if(slides < 4) {
            $('#galleryLeft').css("display", "none");
            $('#galleryRight').css("display", "none");
            $('#gallery_container').css({
                "padding": "0"
            });
        }
    });
})(jQuery);

Maybe notable is that the gallery_container is responsive. The slider is placed inside a column.

like image 833
paulhaem Avatar asked Aug 19 '16 08:08

paulhaem


1 Answers

Simple and nice solution that worked for me, after some wasted hours:

window.addEventListener('load', () => {
// init swiper here
}, false);

The load event is fired when the whole page has loaded, including all dependent resources such as stylesheets and images.

Documentation:
https://developer.mozilla.org/en-US/docs/Web/API/Window/load_event


If this doesn't work for you, make sure you check out the thread where I found this fix:
src: https://github.com/nolimits4web/swiper/issues/2218#issuecomment-509683102

There are other possible solutions (eg: Browser extensions could also cause this problem):

Cheers, I hope this helps somebody!

like image 173
Michael Schober Avatar answered Oct 18 '22 00:10

Michael Schober