How To Use Slick To Create A Carousel
JavaScript
08/10/2019
My favorite go-to CSS framework is Bootstrap and I'm sure it is for many others, too. However, once in a while the components of such a framework are too basic or don't fulfill your requirements adequately. In this case, it's best to use another more dedicated library which offers you more options. Recently, I came across such a situation while trying to build a carousel. I found a fantastic jQuery library called Slick, claiming it's the last carousel you'll ever need. A pretty bold statement if you ask me! 👀 Well, in this tutorial, I'll be showing you how to use Slick to create a carousel as well as point out some of its quirks and errors that I encountered along the way.
Installation
Every journey must start somewhere and Slick is no exception! For the installation, there are two options: either using a CDN or a package manager.
CDN
Slick offers two option when it comes to using a CDN. Make a choice:
Afterwards, simply insert the CSS as links into the HTML page head
and the JavaScript just before your closing body
tag.
<head> <link rel="stylesheet" type="text/css" href="//cdn.jsdelivr.net/gh/kenwheeler/slick@1.8.1/slick/slick.css"/> <!-- Add the slick-theme.css if you want default styling --> <link rel="stylesheet" type="text/css" href="//cdn.jsdelivr.net/gh/kenwheeler/slick@1.8.1/slick/slick-theme.css"/></head><body> <!-- Some other code right here --> <script type="text/javascript" src="//cdn.jsdelivr.net/gh/kenwheeler/slick@1.8.1/slick/slick.min.js"></script></body>
Et voilà! You're ready to use it. 😊
Package manager
If you prefer installing the library via a package manager, you've got several options as well.
# Yarnyarn add slick-carousel
# Bowerbower install --save slick-carousel
# NPMnpm install slick-carousel
Next, you have even more options! Optionsception... 🤯 First, you can insert the relevant CSS and JavaScript files into your HTML page the same way as in the previous section. Only this time, you would be fetching the files from your node modules folder.
On the other hand, my preferred way is to directly import the files into the main (S)CSS and JavaScript files of your project. This is especially recommended in conjunction with tools like Webpack and Gulp.
// main.scss -- I'm using Wepback sass-loader@import "~slick-carousel/slick/slick";@import "~slick-carousel/slick/slick-theme";
// main.jsimport 'slick-carousel/slick/slick';
Alright, now that we've successfully installed it, it's time to show how things are actually done in Slick. 😋
Understanding the basics
With the Slick carousel 🎠 library, you have a ton of features at your disposal, yet a tad too many to actually go over them all. But honestly, that's not my goal! Instead, I want simply to help you understand how the library works and how to read its documentation.
The code
Let's assume you're starting off with several images and you want to turn them into a beautiful carousel. How do you proceed?
<img src="/image-1.png" alt="Image 1"><img src="/image-2.png" alt="Image 2"><img src="/image-3.png" alt="Image 3">
Well, first we have to prepare the HTML layout of our images in such a way that it allows Slick to turn it into a carousel. We do this by adding 2 div
layers to our collection of images, with the most outer layer containing a class name your choice.
<div class="my-carousel"> <div><img src="/image-1.png" alt="Image 1"></div> <div><img src="/image-2.png" alt="Image 2"></div> <div><img src="/image-3.png" alt="Image 3"></div></div>
The class of our outer div
is particularly important ❗, because we use it to tell Slick where our carousel is, which we do so as follows.
$('.my-carousel').slick({ // setting-name: setting-value});
After selecting our carousel with the jQuery selector, we apply the slick()
function to it and let the library do its magic... 🦄. By default, Slick will create a single item carousel with navigation arrows. But this isn't where the story ends yet, because we can still tell Slick how to configure our carousel. And we do so by passing in an object with key-value pairs of settings.
The features
Alright, so let's say I want to create a responsive multi-slide carousel. Which settings would I need to enable? 🧐
First off, let's enable multiple slides in our carousel. As shown above, the key slidesToShow
is responsible for this feature and takes a value of type integer
, which has 1 set as its default. How about we change that to 2?
$('.my-carousel').slick({ slidesToShow: 2,});
Next up, making our carousel responsive! Again, as shown in the image above, the key responsive
takes an object containing breakpoints and a respective settings object. At first, the structure of this object might be a bit difficult to guess, but fortunately we can consult a demo with some code on their page.
How about we only show 1 slide for mobile? 📱
$('.my-carousel').slick({ slidesToShow: 2, responsive: [{ breakpoint: 500, settings: { slidesToShow: 1, } }]});
This little demonstration could go on forever, but at this point I think you get the gist (I hope 😅). I recommend taking a look at the documentation and exploring the various settings that are available.
Bugs galore!
No piece of software is without its flaws and while trying out Slick, I came across two bugs which provided me quite a few headaches...
Not rendering within a hidden div element
When I was first using Slick, I placed it in a hidden div element that could be toggled on and off. To my surprise, the carousel wasn't rendering until I clicked on one of the navigation buttons, as seen in this example. 👈
Luckily, someone else already experienced this issue. As it turns out, the width of the carousel slides are automatically computed based on the parent element, which turns out to be 0 if it is hidden. Unfortunately, this issue was never resolved! (╯°□°)╯︵ ┻━┻
However, I did come up with a quick and dirty workaround. Instead of initializing the carousel on page load, it will be initialized upon clicking the element responsible for making the carousel's parent element visible.
$('#button-toggle').click(() => { setTimeout(() => { $('.my-carousel').slick({ // settings here }); }, 200);
setTimeout(() => { $('.my-carousel').removeClass('invisible'); }, 250);});
In my little hack, I had to add a teeny tiny delay or the code wouldn't run. Furthermore, in order to hide the jittery rendering from the user, the carousel itself is invisible by default and only made visible after the rendering has been completed. Now, whenever you click the button, it seems like there's a minuscule delay in showing the carousel. Another dirty 😏 trick is to introduce a fade-in, et voilà! It's like there never was a bug in the first place.
Webpack production build error
If you're importing Slick's SCSS with the @import
statement and are using Webpack as well, you are in for a surprise when building your project for production.
ERROR in ./node_modules/css-loader!./node_modules/postcss-loader/lib!./node_modules/sass-loader/lib/loader.js!./sass/app.scss Module not found: Error: Can't resolve './ajax-loader.gif' in '/Users/Vishal/Documents/Work/nf-core/sass' @ ./node_modules/css-loader!./node_modules/postcss-loader/lib!./node_modules/sass-loader/lib/loader.js!./sass/app.scss 6:89679-89707
Zoinks! 😥 However, there is a solution!
Simply add these two lines before your import statements:
$slick-font-path: "~slick-carousel/slick/fonts/"; // To add$slick-loader-path: "~slick-carousel/slick/"; // To add
@import '~slick-carousel/slick/slick';@import '~slick-carousel/slick/slick-theme';