Henrique M. Henrique M. - 9 days ago 6
Javascript Question

jQuery - Cloud9 Carousel - goTo function

I was trying to achieve a

goTo(itemIndex)
function with Cloud9 Carousel. You see, Cloud9 carousel has a built-in function
go(x)
that moves the carousel
x
times you have defined. But what I am trying to achieve is to GO to a specific item in the carousel, not a
x
time slide changes. For example, if you put 3 in the
go function
the carousel will roll 3 times. I need something to GO to a specific item, like the markdown below:

<li id="item1">Example 1</li>
<li id="item2">Example 3</li>
<li id="item3">Example 2</li>


I need something like
goTo(".item2")
or perhaps
goTo(itemIndex)
. We can achieve an item index by selecting it nearest neighbor from the one that is being show at the moment. See:

$("#carousel").data("carousel").nearestIndex();


that will provide an
integer
which corresponds the item being show at the moment, so we can calculate the others indexes by giving both positive and negative parameters.

Please, if someone consider giving me some light on that, the github link for the Cloud9 Carousel project is: https://github.com/specious/cloud9carousel

Answer

you can use this function below:

where hits is the array of carousel items

function goto(item){
  if( hits.length !== 0 ) {
        var idx = hits.index(item);
        var count = hits.length;
        var diff = idx - ($("#mycarousel").data("carousel").floatIndex() % count);
        if( 2 * Math.abs(diff) > count )
        diff += (diff > 0) ? -count : count;
       $("#mycarousel").data("carousel").destRotation = $("#mycarousel").data("carousel").rotation;
        $("#mycarousel").data("carousel").go( -diff );

  }

}

hope it will help