Search code examples
phpjqueryowl-carousel-2

Owl Carousel Current Slide and Number of Slides WITH loop option (php)


So I've looked at a few questions so far, and none of these I've seen have really helped me get to my solution.

I need to get a counter on my slider that's using Owl Carousel. I need to get a current slide count and the number of items in the slider.

The thing is, that I am telling the slider to loop back to the beginning when it hits the last slide.

Some of the code examples I've looked at work, except for one thing. It seems Owl Carousel adds 2 items at the beginning and 2 items at the end, with the class cloned appended to them. That messes with the code counts I've been using.

I've tried to isolate the cloned count and that works, but the currentIndex is where I am falling into problems. Trying to get that count to be accurate isn't working. If I have say 4 slides, currentIndex starts at 3 and goes up to 8 while totalItems shows 4.

Any help is appreciated!

I am using OwlCarousel 2

Here is the code I am using:

var = mapSliderOptions = {
        loop: true,
        margin: 0,
        items: 1,
        autoWidth: false,
        mouseDrag: true,
        touchDrag: true,
        dots: false,
        onInitialized  : counter, //When the plugin has initialized.
        onTranslated : counter,
        responsive: {
            0: {
                autoplay: true,
                autoplayTimeout: 5000,
                autoplayHoverPause: true
            },
            768: {
                autoplay: false,
                items: 1
            }
        }
    },

function counter(event) {
    var totalItems = $('.owl-item:not(.cloned)' ).length;
    var currentIndex = $('div.active').index() + 1 ;

    $('#counter').html("item "+ currentIndex +" of " + totalItems);
}


$('.map-hero-slider').owlCarousel( mapSliderOptions );

Solution

  • So this answer is for those who are using php and running a foreach loop.

    What I did was I set the data-dot with the incremental number. I then took a count of the number of items in the array, and passed that through as the final count of items.

    Then calling to the container and with some position absolute for the CSS, I was able to "trick" the front end viewer into the count in a sense.

    Not very effective, but it works for me.