DEV Community

Cover image for HOW TO CREATE A SIMPLE SLIDER WITH VANILLA JAVASCRIPT
Covydev
Covydev

Posted on • Updated on

HOW TO CREATE A SIMPLE SLIDER WITH VANILLA JAVASCRIPT

Sliders are one of the common features websites have. This tutorial will show you how to make a simple slider.

The first step is to create the HTML structure for the slider using the unordered list and list item tags.

<div class="slider-container">
<ul class="slider">
<li><img src="image1.jpg"></li>
<li><img src="image2.jpg"></li>
<li><img src="image3.jpg"></li>
</ul>
</div>

Next, you’ll style it with some basic CSS. The first thing we’ll do is style our slider-container and slider classes.

.slider-container {
width: 600px;
height: 400px;
overflow: hidden;
}

.slider {
list-style: none;
margin: 0;
padding: 0;
width: 1800px;
position: relative;
left: 0;
transition: left 0.5s;
}

.slider > li {
float: left;
}

.slider > li > img {
width: 600px;
height: 400px;
}

Next, we'll add some JavaScript to make the slider functional. There are two logic involved here; displaying the next slide when the forward arrow is clicked and displaying the previous slide when the backward arrow is clicked.

const slider = document.querySelector('.slider');
const prevBtn = document.querySelector('.prev');
const nextBtn = document.querySelector('.next');
let currentPosition = 0;
const step = 600;

The moveSlider function updates the current position of the slider and sets the left position of the slider element to move it left or right.

function moveSlider(direction) {
if (direction === 'prev') {
currentPosition += step;
} else {
currentPosition -= step;
}
slider.style.left = currentPosition + 'px';
}

Add event listeners to the buttons that calls the moveSlider function with the appropriate direction.

prevBtn.addEventListener('click', function() {
moveSlider('prev');
});

nextBtn.addEventListener('click', function() {
moveSlider('next');
});

With these simple steps, you will be able to create a simple slider. It is possible to add other features and functionalities to it, but we’ll stop here in this tutorial.

Top comments (1)

Collapse
 
lambstar profile image
lambert-naaman

beautiful