Im trying to add class on class on first & last child element with ONLY .active class. I found the code here:
JavaScript
x
36
36
1
jQuery(document).ready(function($) {
2
3
var carousel = $(".latest-work-carousel");
4
carousel.owlCarousel({
5
loop : true,
6
items : 3,
7
margin:0,
8
nav : true,
9
dots : false,
10
});
11
12
checkClasses();
13
carousel.on('translated.owl.carousel', function(event) {
14
checkClasses();
15
});
16
17
function checkClasses(){
18
var total = $('.latest-work-carousel .owl-stage .owl-item.active').length;
19
20
$('.latest-work-carousel .owl-stage .owl-item').removeClass('firstActiveItem lastActiveItem');
21
22
$('.latest-work-carousel .owl-stage .owl-item.active').each(function(index){
23
if (index === 0) {
24
// this is the first one
25
$(this).addClass('firstActiveItem');
26
}
27
if (index === total - 1 && total>1) {
28
// this is the last one
29
$(this).addClass('lastActiveItem');
30
}
31
});
32
}
33
34
35
});
36
It does work, however my problem is that the firstActiveItem class is only applied inside the first carousel and the lastActiveItem class inside second carousel.
How do i make it applies on all carousel regardless of how many carousel i have with same class?
Here’s my complete code fiddle: https://jsfiddle.net/tarantadakadin101/xf54zsau/39/
Advertisement
Answer
You can iterate over .owl-carousel
elements and find the target element from the current .owl-carousel
‘s children on every iteration. With this approach no matter how many carousels exists on the page. like this:
JavaScript
1
5
1
$('.owl-carousel').each(function(){
2
$(this).find('.owl-stage .owl-item.active:first').addClass('firstActiveItem');
3
$(this).find('.owl-stage .owl-item.active:last').addClass('lastActiveItem');
4
})
5