If you’re just looking for a CSS based solution without clicks, I’ve got you covered in this post:
How to create a horizontal scrolling menu with and without flex using CSS (or SCSS)?
Let’s add the simple HTML container and contents inside. I have tried to include links since mostly we need this kind of scrolling with a bunch of links. Also, add the buttons to indicate the scrolling direction.
Currently the width is 100% so no need to scroll. Let’s make it a smaller window where the content is required to scroll. Also, let’s make a bit nice looking with minimal style changes.
As you must have noticed, the scrolling is already working when try to slide left or right using mouse pad.
Here’s the function and working demo:
Let’s understand line by line.
In the function itself, we are getting the main container using getElementById. I have set the variable scrollCompleted to 0 since initially there won’t be any distance covered.
After that I am using setInterval method to create the sliding effect in timely manner. You can change the speed of the scroll by changing the setInterval function time.
Inside the setInterval function, I am just checking if the variable passed on the click was left or right and according to that value I am adding to subtracting a specific value — which you can change as per your requirements. I am using scrollLeft to do so.
Also, everytime we add or subtract a value, we need to increment the value of scrollCompleted variable since that will keep an eye on distance covered (scroll completed).
Finally, we need to stop scrolling at a certain point which in this case I am stopping the scroll when it covers 100px. Keep in mind that I am talking about a stopping on a single click that means on a single click I am making the content shift 100px left or right based on the click.
That’s it. After each click it will cover 100px and it’ll stop at the end when there is no more distance to cover.
There are few ways to do the same horizontal scrolling. This is just one way to do it.