Carousels pt. 2: Building a JS carousel from the ground up
Apr 4, 2016
I recently built a website for my friend Kevin to promote his skills, one of them being photography. He asked for an image carousel to show off some of his photos—so, instead of picking up one of the thousands of existing image carousel libraries, I decided to roll my own. You know, for kicks.
I wanted to keep the markup dead simple because, when I was starting out with web dev, I actually found a lot of the carousel libraries out there to be overly complicated, some with really weird markup requirements. So, after some thought, I came up with the following structure for the markup:
So what’s happening is the JS finds our div#fancy-carousel, creates two new divs, each stacked on top of each other, and uses the top (as in z-order) one to house the controls—the previous and next arrows.
The div underneath (let’s call it the ‘display div’) is responsible for displaying the current image. I created an array out of the image sources, which is then applied as the display div’s background image. When the next arrow is clicked, the next image source in the array is set as the display div’s background. Clicking the previous arrow sets the background image to the previous item in the array.
One thing I wanna point out is that a fancy-carousel–active class is being added to the main carousel wrapper, and a hide class is being added to the img elements as they go through the for loop that creates the array of image sources. This is so we can conditionally style the carousel if the JS runs. If you open up the Codepen example on the Codepen site and delete all the JS code, you’ll see that the images render how they would normally render on the page.
So here’s the final JS code, with comments to explain what’s going on.
So yeah, there you go. HTML, SCSS, and vanilla JS carousel! I’m pretty happy with how this turned out. It works super well on mobile as well as desktop, gracefully degrades if someone doesn’t have JS turned on for whatever reason, and is super easy to integrate.
That said, there are three things I want to do to improve this. For one, we don’t need to load all the images right away. Ideally, the images would load as they’re needed. Secondly, I would like to add swipe support so that you don’t have to tap the arrows on touchscreens. Finally, I’d like to make the whole thing class-based instead of ID based. As is, this wouldn’t work if you needed more than one carousel on screen at a time.
Well, that’s it for this post! If you read this far, thanks for sticking with this and I hope you learned something from this write-up.