Skip to content

Instantly share code, notes, and snippets.

@modcab
Created October 6, 2016 09:21
Show Gist options
  • Save modcab/6ad26cdd87d0dec15c8f517b2223c023 to your computer and use it in GitHub Desktop.
Save modcab/6ad26cdd87d0dec15c8f517b2223c023 to your computer and use it in GitHub Desktop.
Owl carousel, with loop = true, get the right current slide on 'changed' event
$(carousel_selector)
.owlCarousel(owlOptions)
.on('changed.owl.carousel', function(e) {
// Number of items, not counting cloned ones.
var count = e.item.count;
// When carousel is infinite,
// there's a certain offset to the first item.
// We'll try to remove it to do our calculations.
var offset = Math.floor((count + 1) / 2);
// This posittion index includes some offset.
var index = e.item.index;
if (index > 0) {
index -= offset;
}
// If the index is still bigger than the number of items
// (or equal, since it starts at 0),
// It must be the first element, so let's remove that offset, too.
if (index >= count) {
index -= count;
}
});
@SergeyMell
Copy link

This works good except when triggering prev.owl.carousel event - in this case shows one less.

@denistrator
Copy link

denistrator commented Sep 24, 2020

@aguasingas thanks for the solution!

This works good except when triggering prev.owl.carousel event - in this case shows one less.

see the fix:

getActiveSlideIndex = function (event) {
    if (!event.item) {
        return null;
    }

    var count  = event.item.count,
        offset = Math.floor((count + 1) / 2),
        index  = event.item.index;

    if (index > 0) {
        index -= offset;
    }

    if (index >= count) {
        index -= count;
    }

    if (index < 0) {
        index = count - 1;
    }

    if (count === 2) {
        index = index === 0 ? 1 : 0;
    }

    return index;
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment