Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iDangerous Swiper, subsequent destroy() and reInit() methods

According to the directions provided as an answer here...

iDangerous Swiper plugin reset slides

I'm trying to do something like this:

http://jsfiddle.net/monastic/ydKn2/17/

<div id="slide-repo">
    <div class="swiper-slide">
        <img src="http://dummyimage.com/100x100/000/fff.jpg" />
    </div>
    ...................   
</div>

<div>
    <button id="update-slides">Update Slides</button>
</div>

<div class="swiper-container">
    <div class="swiper-wrapper">
        <div class="swiper-slide">
            <img src="http://dummyimage.com/100x100/ff0000/fff.jpg" />
        </div>   
        .................
    </div>
</div>


var mySwiper = new Swiper('.swiper-container', {
     mode: 'vertical', 
     loop: true,
     loopAdditionalSlides: 5,
     centeredSlides: true,
     slidesPerView: 2,
     initialSlide: 0,
 });

$('button#update-slides').on('click', function(){

    var swiperWrapper = $('.swiper-wrapper'),
        newSlides = $('#slide-repo').children('.swiper-slide').clone(true);

    mySwiper.destroy();
    swiperWrapper.empty().append(newSlides);
    $('.swiper-wrapper').attr('style', '');
    mySwiper.reInit();

});

But console is returning 'Cannot read property 'init' of null'.

Any suggestions?

like image 424
monastic Avatar asked Jul 12 '14 17:07

monastic


1 Answers

I believe this is because you're calling mySwiper.destroy() and therefore can't run reInit(). The documentation says reInit is for resetting when you've added or removed slides. But here you're calling reInit on an element that is no longer a swiper.

Instead, you could re-create the swiper each time. (I'm not sure why just calling removeAllSlides then reInit does not keep the same settings.)

  var settings = {
    mode: 'vertical', 
    loop: true,
    loopAdditionalSlides: 5,
    centeredSlides: true,
    slidesPerView: 2,
    initialSlide: 0,
  },
  mySwiper = new Swiper('.swiper-container', settings);

$('button#update-slides').on('click', function(){

    var swiperWrapper = $('.swiper-wrapper'),
        newSlides = $('#slide-repo').children('.swiper-slide').clone(true);

    mySwiper.destroy();
    swiperWrapper.empty().append(newSlides);
    $('.swiper-wrapper').attr('style', '');
    mySwiper = new Swiper('.swiper-container', settings);

});

Fiddle: http://jsfiddle.net/L2HJK/2/

like image 140
cjspurgeon Avatar answered Sep 21 '22 13:09

cjspurgeon