slick Carousel - Hide and Show Previous / Next Buttons
I was using the excellent slick Carousel and needed to implement next and previous buttons to move the carousel in the desired direction, but also had to show and hide these buttons depending on the current slide as I didn't want to use the infinite functionality in this scenario.
First off, initialise the plugin using your desired options, I'd say that these are the minimum requirement but in this case I also had arrows
set to false
, dots
set to true
and was also using the lazyLoad
option:
$('.steps').slick({
infinite: false,
slidesToShow: 1,
slidesToScroll: 1
});
Then use the slick api to move the carousel when buttons are clicked:
$('.next').click(function() {
$('.steps').slick('slickNext');
});
$('.previous').click(function() {
$('.steps').slick('slickPrev');
});
and, finally:
$('.steps').on('beforeChange', function(event, slick, currentSlide, nextSlide) {
if (nextSlide == slick.slideCount - 1) {
$('.next').hide();
$('.previous').show();
} else if (nextSlide != slick.slideCount - 1 && nextSlide != 0) {
$('.next').show();
$('.previous').show();
} else if (currentSlide == 0 || nextSlide == 0) {
$('.next').show();
$('.previous').hide();
}
});
I used beforeChange
because using the afterChange
meant the showing and hiding didn't happen until what felt like to be too late, since the new slide has to be in place before that code is executed.