I’ve recently been working on a project where I need to implement a slideshow/carousel. I searched on google but didn’t find the carousel with multiple features. So, I thought of creating one on my own.
Here’s an example of what it looks like:-
HTML
Let’s create the basic HTML structure for the carousel.
- Create
div
with classcontainer
. - Inside this
div
create anotherdiv
with classcarousel-view
.
- A button for the left scroll of the slideshow.
- A div to hold the slideshow items with classitem-list
.
- Another button for the right scroll of the slideshow.
CSS
Now, let’s come to the CSS part. Here first we need to set up the base.
The following Image illustrates how the CSS structuring is done.
Now let's look into this Item-list
.
Since it is a horizontal slideshow we need to align items horizontally and to do this there are multiple ways but I am going with display:flex
property since it also lets me add spacing between the items.
Here is a quick look at the properties we need to apply to this container.
So, basically what we have here is a container with list of items having scrollable overflow
overflow:auto
and the number of items you need to show in the window is determined by the width of the slideshow.
Now, let’s talk about the magic spell we are using here.
This property is used to control the scrolling of our items.
The effect we wanna achieve here is to make sure an item is either entirely inside or outside from the left of the window.
For creating a vertical slider you can use scroll-snap-type: y mandatory
You can learn more about the scroll-snap property here.
Tip: To hide the scroll but keep the functionality we can do it like this
JavaScript
Its time to implement the functionalities of buttons:
- Get
nextButton
,prevButton
&itemList
object from document usingdocument.getElementById()
function. - Now implement item scrolling on click using
eventListener
.
- Whenever a user interacts with a button its
addEventListener
will be triggered and passing event type asclick
ensures that the callback function will execute only on click. - Now, In the callback function, we are decreasing & increasing the value of
scrollLeft
property to slideitemList
right and left.
Here is the complete code and demo for the slideshow:
I appreciate you taking out time and reading this; please share it with your friends and family if you found it helpful, click on the follow button to support me.
Let’s connect on Twitter. I’d love to know my audience more and build a community :)
Let me know your takeaways and other topics you would like me to write about in the comment section — I am eager to see what you have to say.
I hope this helps you, and have a nice day!