user1374796
user1374796

Reputation: 1582

jQuery cycle2: move through slides on scroll

I'm currently using the Cycle2 plugin to create a slideshow (http://jquery.malsup.com/cycle2/), instead of triggering the slide change on click I want to trigger it when you scroll. Essentially I'm trying replicate something like this: http://loris-cormoreche.com but with the cycle2 plugin.

I have a codepen set up to demonstrate the problem: http://codepen.io/neal_fletcher/pen/NrRdmP If you scroll you'll see the problem I'm having, the images keep flickering and it cycles through more than one image at a time as well, in general just quite buggy. The code I currently have is as follows:

$('.cycle-slideshow').on( 'DOMMouseScroll mousewheel', function ( event ) {
    if( event.originalEvent.detail > 0 || event.originalEvent.wheelDelta < 0 ) { //alternative options for wheelData: wheelDeltaX & wheelDeltaY
        $('.cycle-slideshow').cycle('next');
        console.log('Down');
    } else {
       $('.cycle-slideshow').cycle('prev');
       console.log('Up');
    }
    //prevent page fom scrolling
    return false;
});

Any suggestions or ways to improve on this would be greatly appreciated!

Upvotes: 1

Views: 562

Answers (1)

Linus Aronsson
Linus Aronsson

Reputation: 341

The reason why it's buggy is because the event is triggered on every "scroll-click" or whatever you want to call it. So when you scroll you are triggering it several times which makes it choppy like that.

I fixed it in this codepen: http://codepen.io/LinusAronsson/pen/EygWpd

What I did was to change the jQuery to the following:

var scrollDisabled = false;
$('.cycle-slideshow').on('DOMMouseScroll mousewheel', function(event) {

 if (scrollDisabled)
     return;

  if (event.originalEvent.detail > 0 || event.originalEvent.wheelDelta < 0) { //alternative options for wheelData: wheelDeltaX & wheelDeltaY
  $('.cycle-slideshow').cycle('next');
    console.log('Down');
  } else {
    $('.cycle-slideshow').cycle('prev');
  console.log('Up');
    }
   //prevent page fom scrolling

   scrollDisabled = true;
   setTimeout(function(){scrollDisabled = false;}, 1200);

});

I basically turn of the mousewheel event for 1200 milliseconds after it has been used, which is enough of a delay for it to not be triggered before the next picture has come into the view.

Upvotes: 1

Related Questions