Im trying to add class on class on first & last child element with ONLY .active class. I found the code here:
jQuery(document).ready(function($) { var carousel = $(".latest-work-carousel"); carousel.owlCarousel({ loop : true, items : 3, margin:0, nav : true, dots : false, }); checkClasses(); carousel.on('translated.owl.carousel', function(event) { checkClasses(); }); function checkClasses(){ var total = $('.latest-work-carousel .owl-stage .owl-item.active').length; $('.latest-work-carousel .owl-stage .owl-item').removeClass('firstActiveItem lastActiveItem'); $('.latest-work-carousel .owl-stage .owl-item.active').each(function(index){ if (index === 0) { // this is the first one $(this).addClass('firstActiveItem'); } if (index === total - 1 && total>1) { // this is the last one $(this).addClass('lastActiveItem'); } }); } });
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:
$('.owl-carousel').each(function(){ $(this).find('.owl-stage .owl-item.active:first').addClass('firstActiveItem'); $(this).find('.owl-stage .owl-item.active:last').addClass('lastActiveItem'); })