Create a JavaScript Horizontal Image Slider

An Object Is A
3 min readJul 30, 2020

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:

Create a FLEX BOX with many images displayed horizontally in one row.
Create an HTML DIV element that will hide all of the images except the one we want to show the user.

Let’s begin.

Let’s start by creating that flex box.
We’ll create a flex box to wrap around individual cards or images…

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

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…

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.

We’ll create two buttons, Next and Previous. We’ll also need a way to keep track of which card the user is on.
All we need to do is translate our slider left or right..

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

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…

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

--

--