Create a JavaScript Horizontal Image Slider

The basics in organizing your image gallery on a horizontal carousel.

Want to know how to make this slider RESPONSIVE?

The general idea of what we’re going to do is this:

Let’s begin.

Image for post
Image for post

Next, let’s create that view-port to hide all of the images except for the one we want to show the user…

Image for post
Image for post

Now, to set ourselves up for success — meaning an image slider that can go infinitely left or right — we need to clone the first and last cards then put a copy of the first card at the end of our slider and a copy of the last card at the beginning of our slider…

Image for post
Image for post

Note: because we’ve now added two repeated cards in our slider, the main card we want to focus on is shifted off by 1, we need to re-shift it back to the original first card…so we translate the entire flex box left by the width of one card (800px)

Let’s move on to moving this slider.

the width of a card (800px) * ‘the card to move to’.

Image for post
Image for post
Note:
the ‘if’ conditionals make sure the user can’t slide past the beginning or end cards;
the timeout is just there so the user can’t spam the buttons

Finally, we implement logic, in our button listeners, to make our slider scroll back to the beginning or back to the end if the user goes all the way to the right or left…

Image for post
Image for post

If you would like a more in-depth guide, check out my full video tutorial on YouTube, An Object Is A.

(HTML/CSS) Create a Horizontal Image Carousel

Written by

Learning to code…

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store