There are tons of tutorials on making an image slider or image carousel in JavaScript and in numerous frameworks. In this article, we will create a custom image slider with HTML, CSS, and JavaScript that you can use anytime for your projects.
What is an Image slider?
An Image Slider is simply an expedient way to show multiple images which are relevant to your website and can draw more visitors to your site.
Let’s begin with creating the image slider.
HTML CODE 👇🏾
In the HTML code, we will be creating a couple of things.
- First, we will link the icons(next button and previous button) we are going to use.
- Next, we then create a parent div with a class of “slider”.
- Next, we will then create another div with a class of “slider__container” to house the images
- We will then add three images inside the class of “slider__container”. You can also add as many images as you want.
- We will also create another div outside the class of “slidercontainer” with a class called “sliderbuttons”
- Lastly for the HTML code, we will create a two-button individually with a class called “prev-btn” and “next-btn” and will also add the icons for them. Here is the complete HTML code 👇🏾
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link rel="stylesheet" href="../css/style.css" />
<!-- Link icons from from font awesome icons -->
<link
rel="stylesheet"
href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.1.1/css/all.min.css"
/>
<title>Image slider</title>
</head>
<body>
<div class="slider">
<div class="slider__container">
<img
src="./Img/dariusz-sankowski-3OiYMgDKJ6k-unsplash.jpg"
alt="travel-1"
/>
<img
src="./Img/dino-reichmuth-A5rCN8626Ck-unsplash.jpg"
alt="travel-2"
/>
<img
src="./Img/pietro-de-grandi-T7K4aEPoGGk-unsplash.jpg"
alt="travel-3"
/>
</div>
<div class="slider__buttons">
<button class="prev-btn"><i class="fas fa-arrow-left"></i></button>
<button class="next-btn"><i class="fas fa-arrow-right"></i></button>
</div>
</div>
<script src="./script.js"></script>
</body>
</html>
CSS CODE 👇🏾
For the CSS code we will only focus more on these three things which are the “slider” class, “slider__container” class and the “img” tag (which are images) the rest are just basic styling that you easily grasp.
- For the “slider” class, we will add
postion:relative
because we will addpostion:absolute
to the images. We will also addheight:100%
to inherit the height from the body. Lastly, we will addoverflow:hidden
so that one image will be displayed at a time. But it is going to display the last image as the first image. we will see why when we get to the “img” tag. - For the “slider__container” class, we are just inheriting the width and height from its parent div and also adding a transition to make the image go smoothly.
- Lastly for the “img” tag, will add
position:absolute
to the images and when we do that, the last image will automatically be the first image since we addedoverflow:hidden
to the “slider” class but will we reset it back to the first image with javascript.
Here is the complete CSS code 👇🏾
@import url("https://fonts.googleapis.com/css2?family=Poppins:wght@400;500;700&display=swap");
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
img {
width: 100%;
vertical-align: middle;
}
body {
font-family: "Poppins", sans-serif;
height: 100vh;
}
.slider {
position: relative;
height: 100%;
width: 100%;
overflow: hidden;
}
.slider__container {
width: 100%;
height: 100%;
transition: transform 0.4s linear;
}
.slider img {
position: absolute;
top: 0;
bottom: 0;
width: 100%;
}
button {
cursor: pointer;
background-color: #fff;
border: none;
height: 50px;
width: 50px;
border-radius: 50%;
color: #000;
font-size: 1.5rem;
}
.slider__buttons button.prev-btn {
position: absolute;
top: 50%;
left: 15px;
}
.slider__buttons button.next-btn {
position: absolute;
top: 50%;
right: 15px;
}
JAVSCRIPT CODE 👇🏾
This is where the fun part is because we are going to be adding interactivity and functionality to the slider. And we will be breaking it down into different segments.
First segment
In this segment, we will be creating some variables because we will be getting some elements from the DOM (document object model) and storing them into the variables we will be creating.
What we are grabbing from the DOM is the “slider container”, “img” (which are all the images), the “next“ and the “previous” buttons.
After that, we will also create two other variables which are;
A variable called “slideSize” because we will have to get the width of the images and there is a method to get the width which is
getBoundingClientRect().width
here is a link if you want to learn more about it 👇🏾The second variable we will also be creating is a variable called “currentSlide” to track the slides that the images are in.
Here is the complete JS code for what we’ve just talked about 👇🏾
//get the slider container from the DOM
const slider = document.querySelector('.slider__container');
// grab all the images inside the slider container
const slides = Array.from(slider.children);
//get the next and the previous buttons
const prevBtn = document.querySelector('.prev-btn');
const nextBtn = document.querySelector('.next-btn');
// get the size of the first image
const slideSize = slides[0].getBoundingClientRect().width;
// set the current slide to 0
let currentSlide = 0;
Second segment
In this segment, we will also be a function called “reset”.
Inside the “reset” function, we will create a “forEach” loop to set the image next to one another also If you remember when we added position:absolute
to the images, the last image became the first image. we will be using the “reset” function to set it back to its original position
Here is the complete JS code for what we’ve just talked about 👇🏾
// reset slide
function reset() {
// arraging the slides next to each other
slides.forEach((slide, index) => {
slide.style.left = `${slideSize * index}px`;
});
// set the image back to the first image in the DOM
slides[0];
}
reset();
Third segment
In this segment, we will create another function called “moveSlide”.
Inside this function, we are going to give the “slider”(which is the “sliderContianer”) variable a CSS style of translateX(-${currentSlide * slideSize}px)
In the CSS style, we are basically multiplying the “currentSlide” in view by the “slideSize” and moving it horizontally by adding the subtraction sign (-).
But this function will only run when we click on the “next” or “previous” button.
Here is the complete JS code for what we’ve just talked about 👇🏾
// move the slides
function moveSlide() {
slider.style.transform = `translateX(-${currentSlide * slideSize}px)`;
}
Fourth segment
In this segment, we will be creating two functions called “nextSlide” and “prevSlide”
Inside the “nextSlide” function, we increase the “currentSlide” by one and also write an if statement which states that “If the currentSlide is greater than the length of the slides, take one from it and set it back to zero (0)”
After that, we will call the “moveSlide” function that we’ve already created
Inside the “prevSlide” function, we decrease the “currentSlide” by one and also write an if statement which states that “If the currentSlide is less than zero(0), the currentSlide should then be equal to the length of the slides and also take one from it”
We will also call the “moveSlide” function that we’ve already created
Here is the complete JS code for what we’ve just talked about 👇🏾
// move to next slide
function nextSlide() {
currentSlide++;
if (currentSlide > slides.length - 1) {
currentSlide = 0;
}
moveSlide();
}
// move to previous slide
function prevSlide() {
currentSlide--;
if (currentSlide < 0) {
currentSlide = slides.length - 1;
}
moveSlide();
}
Fifth segment
In this last segment, we will addEventListener to the next button and we will listen for a “click” and we will also call the “nextSlide” function so that when we click on the next button, the current image will leave and the next image will show
We are going to also repeat this step for the “prevSlide”
Here is the complete JS code for what we’ve just talked about 👇🏾
// event listeners for the next and previous buttons
nextBtn.addEventListener('click', nextSlide);
prevBtn.addEventListener('click', prevSlide);
Here is the output for the whole JS code 👇🏾
//get the slider container from the DOM
const slider = document.querySelector('.slider__container');
// grab all the images inside the slider container
const slides = Array.from(slider.children);
//get the next and the previous buttons
const prevBtn = document.querySelector('.prev-btn');
const nextBtn = document.querySelector('.next-btn');
// get the size of the first image
const slideSize = slides[0].getBoundingClientRect().width;
// set the current slide to 0
let currentSlide = 0;
// reset slide
function reset() {
// arraging the slides next to each other
slides.forEach((slide, index) => {
slide.style.left = `${slideSize * index}px`;
});
// set the image back to the first image in the DOM
slides[0];
}
reset();
// move the slides
function moveSlide() {
slider.style.transform = `translateX(-${currentSlide * slideSize}px)`;
}
// move to next slide
function nextSlide() {
currentSlide++;
if (currentSlide > slides.length - 1) {
currentSlide = 0;
}
moveSlide();
}
// move to previous slide
function prevSlide() {
currentSlide--;
if (currentSlide < 0) {
currentSlide = slides.length - 1;
}
moveSlide();
}
// event listeners for the next and previous buttons
nextBtn.addEventListener('click', nextSlide);
prevBtn.addEventListener('click', prevSlide);
Here is also a link to the Live site and source code on GitHub if you want to play around with the code. Live site and Source code on GitHub
Conclusion
I really hope this article has helped you to create a custom image slider. You can still take it a step further by making it slide on auto without clicking on the buttons too.
Always remember that the only way to be good at anything is by constant practice