Search code examples
javascriptjquerycarouselcyclejquery-cycle2

Cycle2 Carousel active slide in center


I am using Cycle2 with a carousel pager, in the same way as this demo: http://jquery.malsup.com/cycle2/demo/caro-pager.php

Currently the active slide in the demo is on the left unless you are on the last few slides. What I would like is:

  1. for the active slide to start on the left, on slide 1
  2. then when slide 2 is clicked, the thumbnails don't move but the second thumbnail shows as active.
  3. When slide 3 is clicked, the thumbnails don't move but the third thumbnail (in the middle) becomes active).
  4. When slide 4 is clicked, all thumbnails move one to left and fourth thumbnail (now in the middle) is active.
  5. Same as above for slides 5, 6, 7.
  6. When slide 8 is clicked, thumbnails don't move but eighth thumbnail becomes active (now second from right)
  7. When slide 9 is clicked, thumbnails don't move but ninth thumbnail become active (the last thumbnail on right).

See diagram:

enter image description here

I have copied the demo to a jsfiddle here: http://jsfiddle.net/Qhp2g/1/ but would really appreciate some help as I'm not sure where to start(!) I have tried using data-cycle-carousel-offset="40%" on #cycle-2 as this user tried with a similar problem to me Cycle2: Center Carousel active slide below main slideshow and this does not work because you can't access the last slides and there is space on the left at the beginning.

I assume I may need to change the plugin carousel script - http://malsup.github.io/jquery.cycle2.carousel.js - for my needs but really not sure where to start! Thank you so much for any help.


Solution

  • The thing you will have to do is edit the jquery.cycle2.carousel.js file, and change the transition function. I hard-coded the offset, but you can probably code it to be based off of the percentage that you give it if you want.

    Here are the main changes:

    var offset = 2; //Set the offset of your carousel, for 5 it will be 2.
    //Use this offset to calculate the max and min slide locations.
    var maxCurr = opts.slideCount - (opts.carouselVisible - offset);
    var minCurr = opts.slideCount - (opts.carouselVisible + offset);
    
    ...
    
    //Add the following conditions to account for the new minCurr
    else if (hops > 0 && opts.nextSlide <= minCurr){
        hops = 0;
    }
    else if (hops < 0 && opts.currSlide <= minCurr){
        hops = 0;
    }
    else if (hops > 0 && opts.currSlide < minCurr && opts.nextSlide > minCurr){
        hops = opts.nextSlide - minCurr;   
    }
    else if (hops < 0 && opts.nextSlide < minCurr){
        hops = opts.nextSlide - minCurr;   
    }
    

    See the working fiddle here: http://jsfiddle.net/m66tS/10/