In this post, we will see how to use the unslick
function provided by the Slick Slider library.
The unslick
function allows us to disable the slider functionality at a specific breakpoint, which we can set when initializing the carousel under the responsive option. Here’s how it looks:
$('.slider').slick({
dots: true,
arrows: false,
infinite: true,
speed: 1000,
slidesToShow: 1,
mobileFirst: true,
slidesToScroll: 1,
draggable: true,
centerMode: true,
centerPadding: '30px',
responsive: [
{
breakpoint: 992,
settings: "unslick"
}
// You can unslick at a given breakpoint now by adding:
// settings: "unslick"
// instead of a settings object
]
});
The above code will cause the slider to be disabled when the screen width is greater than 992px, as desired.
However, Slick unfortunately does not automatically reinitialize the slider after it’s been “unslicked”. This means that if we open the page with a screen width smaller than 992px and then resize the screen above this breakpoint, the slider will remain disabled.
Therefore, in this situation, we need to reinitialize the library at the same aforementioned breakpoint. This is achieved by placing the Slick parameters into a variable.
Afterward, we will constantly check the screen width for any changes (resize event), and when we reach the designated breakpoint, we will reinitialize the slider and get it working again.
The code will be in the following style:
const settings = {
dots: true,
arrows: false,
infinite: true,
speed: 1000,
slidesToShow: 1,
mobileFirst: true,
slidesToScroll: 1,
draggable: true,
centerMode: true,
centerPadding: '30px',
responsive: [
{
breakpoint: 992,
settings: "unslick"
}
// You can unslick at a given breakpoint now by adding:
// settings: "unslick"
// instead of a settings object
]
};
const sl = $('.slider').slick(settings);
$(window).on('resize', function () {
if ($(window).width() < 992 && !sl.hasClass('slick-initialized')) {
$('.slider').slick(settings);
}
});
And this will be the result. Decrease the browser width to see how the slider comes into action when reaching 992px, which is the breakpoint defined in line 27. Regardless, here’s the outcome:
For mobile users – to observe the change, you’ll need to view the example on desktop and adjust the browser width.
Up to this point. If you’re not familiar with the library, you can check out this post I wrote about using Slick Slider with ACF, it might help you learn how to use it.