How can I make this slider work with vainilla JS?

I’m looking for advice. What topics do I have to study to make this Slider work on mobile and desktop?


What you are talking about is usually referred to as a carousel (it doesn’t necessarily have to rotate automatically). Implementing a carousel properly (that is, accessibly) actually takes quite a bit of work. My advice would be to find a good one that somebody has already created and done all the hard work for you and either use it directly or at least use it as an example of how to implement your own. A good one to check out is accessible-slick, but it requires jQuery and that might rub some people the wrong way.

If you really want to roll your own you can refer to the ARIA authoring practices for carousels and associated example which includes vanilla JS source code.

I’m sure there are probably other carousel widgets out there if you search for them. The main point is that implementing them properly takes a lot of work and you will need to familiarize yourself with some advance accessibility concepts.

But if you don’t care about accessibility right now and just want to get a bare minimum carousel going then I would suggest you wrap those left/right arrows in <button>s and then add some event handlers to those buttons that manipulate CSS classes which allow you to show/hide the cards as needed.

1 Like

I’ll have a check once in at work and off phone, as it’s a bit hard navigating CodePen

In meantime here are three examples (I have a load more of varying levels of complexity somewhere, but those ones probably most useful). All from about 5-7 years ago when I had to build a load of carousels

Basically pattern generally works, there should be no reason why it doesn’t work cross platform unless you’re doing something weird:

HTML/CSS setup:

  • Outer wrapper element, that will normally be 100%. Set overflow: hidden
  • Inner wrapper element, which should have display: flex set, because it contains a
  • Set of images/elements. Make them all the same size
  • Back/forward buttons can be anywhere

JS setup:

  • store the number of images
  • store the index
  • apply transform:translateX to the inner wrapper element on every move
  • translateX takes a %, and that % relates to the width of the actual element. Each step is 100% / number of images. So the translation is 0 - (index × step) percent.
  • going forward increments the index to a maximum of (number of images - 1)
  • going backwards decrements the index to a minimum of 0


  • carousels are crap for user interaction (ie IRL people often basically ignore everything past the first slide) and crap for accessibility.
  • carousels are also very useful, just avoid putting important content/links etc in them.

you can also check this guide on how to build a slider

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.