Search code examples
javascriptjqueryowl-carousel-2

Using jQuery/js counter with Owl Carousel to display two digits in navigation


I am using Owl Carousel 2 and creating custom navigation which is currently formatted as < 1 / 10 >. I would like to implement two digit numbering, so for numbers less than 10 I need to add a 0 in front. Ideally the formatting would look like this: < 01 / 10 >. I have attempted an if/then but couldn't get it to work with how the counter is written here. Is there a way to modify this code to achieve this format?

JS/jQuery

<script>
$(function(){
var owl = $('.owl-carousel');
owl.owlCarousel({
  items:1,
  loop: false,
  onInitialized  : counter, //When the plugin has initialized.
  onTranslated : counter //When the translation of the stage has finished.
});

$(".next").click(function() {
    owl.trigger('next.owl.carousel');
});
$(".prev").click(function() {
    owl.trigger('prev.owl.carousel');
});

function counter(event) {
   var element   = event.target;
    var items     = event.item.count;     // Number of items
    var item      = event.item.index + 1;     // Position of the current item

  $('.counter').html(item+" / "+items)
}
});
</script>

HTML

<div class="gfoot">
    <div><h5><a class="prev">&lt; </a>
        <span class="counter"></span>
    <a class="next"> &gt;</a></h5></div>
</div>

Solution

  • Try replacing this line:

    $('.counter').html(item+" / "+items)
    

    with this line:

    $('.counter').html((item < 10 ? '0' : '') + item + " / " + items)