Gabbax0r Gabbax0r - 2 months ago 21
CSS Question

Owl carousel active item sould be in the middle JQuery

I have a problem with my owl-carousel. Everything works fine but the active item is the first one on the page not the middle one (the colored is the active one). You can see this in the following screenshot.

Screenshot of owl-caousel

I would like to have the middle item always be the active item.

My JQuery code :

jQuery(".owl-carousel").owlCarousel({
items:3,
loop:true,
nav:true,
responsive:{
0:{
items:1,
stagePadding: 450
},
600:{
items:1,
stagePadding: 450
},
1000:{
items:1,
stagePadding: 450
}
}
});


I found something like this but it doesn work:

jQuery(".owl-carousel").owlCarousel({
items:3,
loop:true,
nav:true,

// THIS IS THE NEW PART
afterAction: function(el){
//remove class active
this
.$owlItems
.removeClass('active')
//add class active
this
.$owlItems //owl internal $ object containing items
.eq(this.currentItem + 1)
.addClass('active')
}
// END NEW PART

responsive:{
0:{
items:1,
stagePadding: 450
},
600:{
items:1,
stagePadding: 450
},
1000:{
items:1,
stagePadding: 450
}
}
});

Answer

Owl carousel adds the .active class to all visible items, not only to one of them.

But when you use the center option only the centered item gets the .center class.

Look at this demo: https://codepen.io/glebkema/pen/Xjryjd

$('.owl-carousel').owlCarousel({
  autoplay: true,
  center: true,
  loop: true,
  nav: true,
});
.owl-item.active > div:after {
  content: 'active';
}
.owl-item.center > div:after {
  content: 'center';
}
.owl-item.active.center > div:after {
  content: 'active center';
}
.owl-item > div:after {
  font-family: sans-serif;
  font-size: 24px;
  font-weight: bold;
}
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/OwlCarousel2/2.0.0-beta.2.4/assets/owl.carousel.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/OwlCarousel2/2.0.0-beta.2.4/assets/owl.theme.default.css">

<div class="owl-carousel">
  <div><img src="//placehold.it/300x300/936/fff/?text=1" alt=""></div>
  <div><img src="//placehold.it/300x300/693/fff/?text=2" alt=""></div>
  <div><img src="//placehold.it/300x300/369/fff/?text=3" alt=""></div>
  <div><img src="//placehold.it/300x300/f63/fff/?text=4" alt=""></div>
</div>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/OwlCarousel2//2.0.0-beta.2.4/owl.carousel.min.js"></script>

Comments