marksy
marksy

Reputation: 64

count the number of items before a class jquery

I have a really basic jquery carousel that outputs this code:

<div class="flexslider">
    <ul class="slides">
        <li><a>red</a></li>
        <li><a>green</a></li>
        <li><a class="flex-active">blue</a></li>
        <li><a>black</a></li>
        <li><a>white</a></li>
    </ul>
</div>
<div id="count"></div>

I want to output the current slide number (slide 3 of 5) but using .index() doesn't seem to work. It keeps coming up as "-1" and won't update as the carousel slides.

var total = $('.carousel li').length;
var current = $(this).find('.flex-active');

$("#count").html($('li').index(current)  + ' of ' + total);

example: http://files.marksy.com/public/slider/index.html

Upvotes: 2

Views: 2824

Answers (4)

Jozzhart
Jozzhart

Reputation: 1322

It's all a bit jumbled, $(this) isn't what your after, also you're finding a child of the li's so it's index will be wrong, need to get it's parent. I've cleaned it up a tad.

http://jsfiddle.net/jozzhart/uMNvB/

var $slides = $('.slides li');
var $current = $slides.find('.flex-active').parent();

var index = $slides.index($current) + 1;
var total = $slides.length;

$("#count").html(index + ' of ' + total);

Upvotes: 2

user2156884
user2156884

Reputation:

O And for your setup:

   var listItem = $(".flex-active").parent();
   var listTotal = $(".slides li").size();
   var listitemNow = $('li').index(listItem);
   listitemNow++;
   $('#count').html('Index: ' + listitemNow + ' of ' + listTotal);

Output:

red
green
blue
black
white

Index: 3 of 5

Upvotes: 0

user2156884
user2156884

Reputation:

Maby something like this to output:

<div class="flexslider">
    <ul id="flex-UL" class="slides">
        <li><a>red</a></li>
        <li><a>green</a></li>
        <li id="flex-active"><a>blue</a></li>
        <li><a>black</a></li>
        <li><a>white</a></li>
    </ul>
</div>
<div id="count"></div>

Its bether workable

Than:

var listItem = $('#flex-active');
var listTotal= $("#flex-UL li").size()
$('#count').html( 'Index: ' + $('li').index(listItem) + ' / ' + listTotal);

Output:

red
green
blue
black
white

Index: 2 / 5

Upvotes: 1

insertusernamehere
insertusernamehere

Reputation: 23580

In your example you're using FlexSlider.

$('.flexslider').flexslider({animation:"slide"});

FlexSlider stores the current slide number and you can use the after-callback to get the this value:

$('.flexslider').flexslider({
    animation: "slide", 
    after: function(slider) {
        alert (slider.currentSlide);
    }
});

You can read more about it in the documentation. It's in the "Advanced"-tab and starts at "The new, robust Callback API".

Upvotes: 0

Related Questions