Question

I am trying to figure out how to limit a jQuery counter dynamically from exceeding the number of items in a list.

Here is my code.

HTML:

<div class="mobile-nav">
            <div class="left-platform-arrow"></div>  
            <div class="counter">
                <span class="number">1</span>
                <span>/</span>
                <span class="label">1</span> 
            </div>    
            <div class="right-platform-arrow"></div>     
        </div>

jQuery:

$('.right-platform-arrow').on('click', function(){
    $('.left li.selected').next().addClass('selected');
    $('.left li.selected').prev().removeClass('selected');
    $('.main .right .pane-open').next().addClass('pane-open');
    $('.main .right .pane-open').prev().removeClass('pane-open');       
    $('.number').text(function(i, t) {
        return Number(t) + 1;
    });
}); 
$('.left-platform-arrow').on('click', function(){
    $('.left li.selected').prev().addClass('selected');
    $('.left li.selected').next().removeClass('selected');
    $('.main .right .pane-open').prev().addClass('pane-open');
    $('.main .right .pane-open').next().removeClass('pane-open');
    $('.number').text(function(i, t) {
        return Number(t) - 1;
    });
}); 
$(".left .label").text(function() {
    return $(this).closest(".left").find("li").length;
});

You can see the current code live at http://clearleap.com/platform/the-clearleap-platform/clearplay/ (it only displays on mobile devices, so view from your cell phone).

The issue is that if you keep clicking the left or right arrow, the number will exceed the maximum number of items. For example, you can make it display 77/5 which is a rather annoying glitch.

How can I resolve this?

Was it helpful?

Solution

if you are doing a ul li list then you could count the max by finding occurence of the ul's children by using

$('ul').children().length;

I have implemented a jsfiddle where this would work here:

http://jsfiddle.net/LKTQT/2/

I have made it so that every time the right button is pressed the value is parsed so that it is recognised as an integer. Then there is an if which makes sure that this value does not exceed the maximum number of children in the list.

(I've just replaced the jsfiddle with a second version which includes a left button example because I noticed that on your site it also allows you to go into negative values).

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