Michelle
Michelle

Reputation: 117

add class to next and previous div in carousel

I'm using Slick and I'm trying to add classes to the next and previous slides in my carousel. The active slide has the class slick-active, so I used this:

$(".slick-active").prev().addClass('prevdiv');
$(".slick-active").next().addClass('nextdiv');

But the problem is that if I go to the next slide, the classes don't move. I've been trying to look for solutions, and saw something about using trigger & bind maybe?

Fiddle: http://jsfiddle.net/ak9Lnrjj/1/ (I made it focus on select, so click on the next or previous slide to make that slide active).

Upvotes: 1

Views: 12706

Answers (2)

gregmac
gregmac

Reputation: 25291

Slick has an afterChange event (I'd link to it but the documentation is awful and doesn't have links).

There is also a $slides property that contains all of the slide elements, so it's possible to find which one is current. This also means in the case of multiple instances on the same page, we're only updating the one that is actually changing.

$('.center')
.on('afterChange init', function(event, slick, direction){
    console.log('afterChange/init', event, slick, slick.$slides);
    // remove all prev/next
    slick.$slides.removeClass('prevdiv').removeClass('nextdiv');

    // find current slide
    for (var i = 0; i < slick.$slides.length; i++)
    {
        var $slide = $(slick.$slides[i]);
        if ($slide.hasClass('slick-current')) {
            // update DOM siblings
            $slide.prev().addClass('prevdiv');
            $slide.next().addClass('nextdiv');
            break;
        }
    }
  }
)
.on('beforeChange', function(event, slick) {
    // optional, but cleaner maybe
    // remove all prev/next
    slick.$slides.removeClass('prevdiv').removeClass('nextdiv');
})
.slick({
  centerMode: true,
  centerPadding: '27%',
  focusOnSelect: true,
  slidesToShow: 1,
  arrows: false,
});

Demo: http://jsfiddle.net/ak9Lnrjj/10/

Upvotes: 9

rrk
rrk

Reputation: 15846

Use slick custom events afterChange and 'init' for changing anything on change or init.

DEMO

$('.center').on('init',function(){
    $(".slick-active").prev().removeClass('nextdiv').addClass('prevdiv');
    $(".slick-active").next().removeClass('prevdiv').addClass('nextdiv');
});
$('.center').slick({
  centerMode: true,
  centerPadding: '27%',
  focusOnSelect: true,
  slidesToShow: 1,
  arrows: false
}).on('afterChange',function(){
    $(".slick-active").prev().removeClass('nextdiv').addClass('prevdiv');
    $(".slick-active").next().removeClass('prevdiv').addClass('nextdiv');
});

Upvotes: 3

Related Questions