Question

I have a number of divs all with the class '.slide' and a scroll to function that scrolls through them when a .slide div is clicked.

See here: http://codepen.io/thomasjwpayne/pen/KFotg

However i'm trying to get the function to work when clicking on the body as opposed to the slide. Also because the slides are displayed as inline-block i need it to scroll to the slide after when the next slide is already fully in the viewport.

Does anyone have any direction on this?

Was it helpful?

Solution

You'd have to keep a tracker somewhere, in my example - I use the body to keep a data-* attribute which stores the current jQuery Object which is currently in view.

var currentSlide = $('body').data( 'current-slide', $('div.slide').eq(1) );

Then switch the $.click() handler from $('div.slide') to $('body'):

$('body').click(function(e){
   e.preventDefault();
   //get the current slide index from the body tag.
   $this = currentSlide.data( 'current-slide' );
   $next = $this.next('div.slide');

   if($next.length) {
        $next.scrollTo($next.attr('id'));
        //Save the next slide as the current.
        $('body').data( 'current-slide', $next );
   } else {
        //Throw us back to the top.
        $('div.slide:first').scrollTo($('div.slide:first').attr('id'));
        //Save the first slide as the first slide, which 
        //Cycles us back to the top.
        $('body').data( 'current-slide', $('div.slide:first'));
   }

   $(".slide a").click(function(e) {
       e.stopPropagation();
   });
});

CodePen Demo: http://codepen.io/anon/pen/tBqhJ

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top