DEV Community

Cover image for Carousel / Slider - Approaches for building custom carousel component
Mykhailo Toporkov
Mykhailo Toporkov

Posted on

Carousel / Slider - Approaches for building custom carousel component

Slides carousel using anchor links

The first approach is based on the use of anchor links, although they are only used to change the slide. The magic behind most all approaches is utilizing the window through which user see some slide. Let's understand this approach, In the picture below we have 3 axes that help us to get an initial position of slides and window through which a user sees one slide:

initial position of slides

Now that a user performs a scroll the slide changes to the next one.

after index change position of slides

however, just a simple scroll won't make the slide be centred inside the window to achieve this we cant use scroll-snap-type CSS property. For the navigation to the desired slide we will use combination with id property for <img /> tag and href for <a> tag.

Slides carousel using slide index-offset

In the second approach, the logic is built around the current slide's index and the offset is applied to a container with slides.
Simple increasing or decreasing the index triggers the change of the translateX value for slider container.

The index-offset approach gives us more flexibility for slide changing, however, it is not so beautiful when It comes to cycled change. Cause when reach the end of the slides next slide will be the first one, which means that the index will be equal to 0. From an animation perspective, we will see the scroll of all slides till the first one... To solve this problem, need to slightly change the work with index.

Slides carousel with cycled offset

In the previous approach with index, we only made offset of the whole container with images which means we had all images in the viewport even when we could not see them. But now I suggest that we have only 3 images in viewport, in general, It will look like:

slides position with index

From here we can change the image we will see next to the needed one without returning to the start when we reach the end... Sounds confusing, doesn't it? What I mean is that next image as prev image is always be rendered depending on the index.

These are the most basic approaches to creating a custom carousel. All of them can be adapted to and used with any framework you like)

Top comments (0)