I am attempting to get the index of the current item in a JCarousel so that I can display the current position within the Carousel to the user. For example, \'13/20\'.
H
Another solution getting the current index of the item with jquery...
//jcarousel item becomes visible
$('.jcarousel').on('jcarousel:visiblein', 'li', function(event, carousel) {
// "this" refers to the item element
itemCount = $(".jcarousel li").length; //1 based
currentIndex = ($( "li" ).index($(this))); //0 based
if(currentIndex + 1 == itemCount) {
alert('last');
}
if(currentIndex == 0) {
alert('first');
}
});
I found this method of highlighting the jcarousel controller that may contain the answer.
It doesn't seem as obvious as I would have hoped from a jQuery plugin to be honest.
There are two callbacks itemVisibleInCallback
and itemVisibleOutCallback
, but they're only going to be useful if you're only displaying one image at a time.
To be honest, as much as I hate to send you down a totally different path, I would highly recommend using the cycle plugin for carousel work as it allows much, much finer customisation that would I could see from my quick look through the jCarousel (sorry jCarousel author - the code itself looks brilliant!).
I too have found that jCarousel returns unusable .first, .last, .prevFirst and .prevLast properties at the times that you need them.
Hence, I had to do it the dirty way and decided to write a function that returns the ID of whichever li tag is currently the first in the container, by reading whether or not it's left-offset is above zero. If so, and it's the first one with an above-zero left position, it's my current slide.
The following code assumes that you've put an id="listitem-N" in the list tags in your foreach() loop, where N is the current iteration.
var currSlide = 0;
function getCurrentCarouselItem(){
$("ul#use-cases li.use-case").each(function(){
var leftPos = $(this).offset().left;
if( leftPos >= 0){
var id = $(this).attr('id').split("-");
currSlide = id[1];
return false;
}
});
return currSlide;
}
The reason I don't return the id in the each() is because each() is a function and the return will only return for that function, not getCurrentCarouselItem().
You can hook into the 'jcarousel:animate' event, and grab the current slide as a jQuery Object.
$('#mycarousel').on('jcarousel:animate', function(event, carousel) {
console.log(carousel._target); // this outputs your current slide as jQuery object.
});