Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

OWL Carousel: Getting index of object that is clicked

So I am trying to use the Carousel for navigation on a UI that I am designing, I'm just wondering if there is a way to easily get the index of one of the div objects within the carousel.

I am trying to make it when I click one of the divs, that it centers it within the carousel, so if I can get the index of the div that has been clicked I can then call the code below to set that as the center item.

var owl = $('.owl-carousel');
owl.owlCarousel();
owl.trigger('to.owl.carousel', NUMBEROFDIVCLICKED);

Image of what i'm trying to do: To-be picture of movement of items

like image 998
XeTK Avatar asked Dec 11 '22 04:12

XeTK


1 Answers

Obviously you speaking about version 2.0 beta because you're using to.owl.carousel. I would not go with the solution from Leif because it won't work in many cases. So this is what you can do:

$('.owl-carousel').on('click', '.owl-item', function(e) {
  var carousel = $('.owl-carousel').data('owl.carousel');
  e.preventDefault();
  carousel.to(carousel.relative($(this).index()));
});

Here is a demo. But please notice it's beta and might change. You have also to use the latest development.

Depend on what plugins your are using (navigation) you have to write the to call like this:

carousel.to(carousel.relative($(this).index()), false, true);

Here are some explanations:

  • $(this).index() is part of jQuery and gives you the position of the clicked item .owl-item within its container.
  • $('.owl-carousel').data('owl.carousel') gives you the plugin object of Owl Carousel, thus you can use the API directly without using the plugin method ($('.owl-carousel').owlCarousel('method', 'arg')) or jQuery events ($('.owl-carousel').trigger('method', ['arg'])).
  • carousel.relative($(this).index()) gives you the relative position of the clicked item. This is always necessary when you have loop activated, which uses cloned items and thus you have more items before you started the plugin.
  • carousel.to() only accepts relative positions.
like image 141
witrin Avatar answered Dec 28 '22 08:12

witrin