Search code examples
javascriptjquerycarouselslideshowowl-carousel-2

How can I get the index of prev and next item in OwlCarousel2?


How can I get the index of the next and prev items in OwlCarousel for setting background images for the next and prev buttons? I made the basic variant of carousel.

$('.cat-slides').owlCarousel({
    items: 1,
    center: true,
    loop: true,
    autoWidth:true,
});

I need to get index's of prev & next for set the img's as background for prev & next buttons.


Solution

  • First it's necessary to understand this carousel library generates "clones" of your slides, placing half the clones before your slides, and the remaining clones after your slides. This is what an example with 12 items looks like:

    owl DOM clones

    So to get the correct index of the button in relation to the active item, you need to subtract half the number of clones from the active item's index. Here's how you'd go about it:

    $(".cat-slides").on('changed.owl.carousel', function() {
        // get the index of the active item
        const activeItem = document.querySelector('.owl-carousel.cat-slides .active');
        const allItems = Array.from(activeItem.parentNode.children);
        const index = allItems.indexOf(activeItem);
    
        // count the clones
        const cloneCount = activeItem.parentNode.querySelectorAll('.cloned').length;
    
        // take the previous/next item's index, then subtract half the clones from it
        const prevButtonIndex = index - 1 - cloneCount / 2;
        const nextButtonIndex = index + 1 - cloneCount / 2;
    
        // get references to the next and previous button elements
        const allButtons = document.querySelectorAll('.owl-dot');
        const nextButton = allButtons[nextButtonIndex];
        const prevButton = allButtons[prevButtonIndex];
    
        // example of how you'd change the background image of each button
        if (nextButton) nextButton.style.backgroundImage = "path/to/next/image";
        if (prevButton) prevButton.style.backgroundImage = "path/to/prev/image";
    });
    

    The next bit you're missing is how to get the previous/next images, but I'm only answering the question you've asked. If anything is unclear, let me know.