3

https://jsfiddle.net/fnethLxm/10/

$(document).ready(function() {
    parallaxAuto()
});
function parallaxAuto() {
    var viewer       = document.querySelector('.viewer.active'),
    frame_count  = 5,
    offset_value = 500;

    // init controller
    var controller = new ScrollMagic.Controller({
      globalSceneOptions: {
        triggerHook: 0,
        reverse: true
      }
    });

    // build pinned scene
    var scene = new ScrollMagic.Scene({
      triggerElement: '#sticky',
      duration: (frame_count * offset_value) + 'px',
      reverse: true
    })
    .setPin('#sticky')
    //.addIndicators()
    .addTo(controller);

    // build step frame scene
    for (var i = 1, l = frame_count; i <= l; i++) {
      new ScrollMagic.Scene({
          triggerElement: '#sticky',
          offset: i * offset_value
        })
        .setClassToggle(viewer, 'frame' + i)
        //.addIndicators()
        .addTo(controller);
    }

    $(".right_arrr").click(function(){
        var block = $(this).siblings('.secondSlider');
        el = block.find(".active");
        elNum = el.attr("data-num");
        if(elNum < block.find('.slide').length) {
            elNum++;
        } else {
            elNum=1;
        }
        hideShow(elNum, block);
        alert('slide №' + elNum)
        scene = scene.destroy(true);
        scene = null;
        controller.destroy(true);
        controller = null;
        parallaxAuto();
    });
    $(".left_arrr").click(function(){
        var block = $(this).siblings('.secondSlider');
        el = block.find(".active");
        elNum = el.attr("data-num");
        if(elNum > 1) {
            elNum--;
        } else {
            elNum=block.find('.slide').length;
        }
        hideShow(elNum, block);
        scene = scene.destroy(true);
        scene = null;
        controller.destroy(true);
        controller = null;
        parallaxAuto();
    });
    function hideShow(num, block) {
        block.find("div.active").removeClass("active").animate({ opacity: 0,},300);
        block.find("div.slide"+num).addClass("active").animate({ opacity: 1,},300);
    }
};

You can see that on 1 and 2 slide plugin work out fine, but on slide 3 it does not work. and error "Cannot read property 'destroy' of null" A few days longer I sit and I can not understand how to fix this?

1 Answers1

2

I see 2 issues:

  • you're setting the scene and the controller to null on every right/left click, and require re-init of it re-calling parallaxAuto;
  • every time you call parallaxAuto you re-bind the listeners.

I took the freedom to rewrite it for you so the listeners will be bound only once: https://jsfiddle.net/j6u6wp7x/. I just isolated the part in which you re-init the controller and the scene so you can call it at the end of the click without re-binding the events.

reallynice
  • 1,289
  • 2
  • 21
  • 41