Shekhar R
Shekhar R

Reputation: 81

How can I add class to the first and last item among the visible items of Owl Carousel 2?

I need to add a class to the first and last item of the currently visible items on Owl Carousel 2.

Upvotes: 2

Views: 14700

Answers (3)

Suraj Lulla
Suraj Lulla

Reputation: 546

Following @Lasithds answer, if you want to add "active" class to the first owl active div, you can use the following:

$('.owl-carousel').on('changed.owl.carousel initialized.owl.carousel', function (event) {
    $(event.target)
        .find('.owl-item').removeClass('first')
        .eq(event.item.index).addClass('first');
})
.owlCarousel({
    loop: false,
    dots: false,
});

Upvotes: 2

Lasithds
Lasithds

Reputation: 2291

I also had the same issue with styling the last active item and couldn't find anywhere for a easy fix. Finally came up with a fix that works for me.

Here's a simple fix that worked for me.

$('.owl-carousel')
  .on('changed.owl.carousel initialized.owl.carousel', function(event) {
    $(event.target)
      .find('.owl-item').removeClass('last')
      .eq(event.item.index + event.page.size - 1).addClass('last');
  }).owlCarousel({
    responsive: {
      0: {
        items: 3,
      },
      768: {
        items: 4,
      },
    }
  });

First item can be easy styled just using css.

.owl-item:not(.active) + .owl-item.active{
   background: red;  
}

Upvotes: 4

Mark Wilson
Mark Wilson

Reputation: 1354

DEMO:

http://plnkr.co/edit/t9URfKq9Mwh9jO705h7u?p=preview

Owl carousel adds a class active to all the visible items. So as you can see I have written a script below to loop through all the owl-item with class active and then using the 0th and last index, I am adding two different classes.

Use the code in your project and you will get the classes added.

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');
            }
        });
    }


});

DEMO:

http://plnkr.co/edit/t9URfKq9Mwh9jO705h7u?p=preview

Upvotes: 10

Related Questions