0

i am using owl carousel 2, where i am using the center function. I have 5 items to be displayed on the carousel. Is it possible using jquery to add classes to find certain divs within the carousel, without having to add ids or classes on the div. http://owlcarousel.owlgraphic.com/demos/center.html

heres my html

<div class="owl-carousel">
  <div class="product"> Your Content </div>
  <div class="product"> Your Content </div>
  <div class="product"> Your Content </div>
  <div class="product"> Your Content </div>
  <div class="product"> Your Content </div>
  <div class="product"> Your Content </div>
  <div class="product"> Your Content </div>
</div>

heres my js

$(document).ready(function () {
$(".owl-carousel").owlCarousel({
    center: true,
    items:5,
    loop:true,
    margin:0,
    responsive:{
        600:{
            items:5
        }
    },
    nav:true

});


});

What i want if you were to view the actual carousel on live would be the addition of these two classes "a" and "b"

<div class="owl-carousel">
  <div class="product"> Your Content </div>
  <div class="product b"> Your Content </div>
  <div class="product a"> Your Content </div>
  <div class="product center"> Your Content </div>
  <div class="product a"> Your Content </div>
  <div class="product b"> Your Content </div>
  <div class="product"> Your Content </div>
</div>

so i am basically trying to locate the divs next to center and the second div next to center

jsg
  • 1,224
  • 7
  • 22
  • 44

1 Answers1

0

There you go, in a 1 minute tryout:

$("#owlSlider").owlCarousel({
  navigation : false,
  autoPlay:true,
  afterMove : function (elem) {
    var lng = $('.product').length,
        a = [],
        b = [];
    if(!!$('.center').length) {
      $('.a, .b').removeClass('a b');
      a.push($('.center').index()-1>=0?$('.center').index()-1:lng-1);
      a.push($('.center').index()+1<lng?$('.center').index()+1:0);
      b.push($('.center').index()-2>=0?$('.center').index()-2:lng-2);
      b.push($('.center').index()+2<lng?$('.center').index()+2:$('.center').index()+2-lng);
      a.forEach(function(item){
        $('.product:eq('+item+')').addClass('a');
      });
      b.forEach(function(item){
        $('.product:eq('+item+')').addClass('b');
      });
    }
  }
});

Live here: http://codepen.io/raduchiriac/pen/doLQdg?editors=101

Next thing is to optimise this a bit, as it's very very ugly.

Radu Chiriac
  • 1,374
  • 3
  • 18
  • 34
  • would this work if the carousel was in motion, so once the next div becomes "center" the classes around it will change – jsg Aug 14 '15 at 13:50
  • You would need to hook to the `afterMove()` callback. I think it should work like in my new edited answer – Radu Chiriac Aug 14 '15 at 14:21