Get the 2024 Yearly Goals and Progress Tracker Notion Template for FREE!

How to Build a Responsive Image Slider with Html, CSS and JavaScript: Step-by-Step Guide

SERIES: JavaScript Projects for Beginners

Updated on: Nov 3, 2023

16 mins read

How to Build a Responsive Image Slider with Html, CSS and JavaScript: Step-by-Step Guide

Hi guys and welcome to the third article in my JavaScript Projects for Beginners Series, a series where I build 10+ beginner-friendly Javascript projects, to test and build your Html, CSS, and Javascript coding skills. In this third article, we are going to learn how to build a Vanilla Js Image Slider using Html, CSS and JavaScriptstarstarstarstarstarstar.

Prerequisites

I am going to assume that you are already familiar with using Html, CSS, and JavaScript and also have a basic understanding of how JavaScript DOM Manipulation works. With that on hand, let's get coding.

giphy.gif

Image from Giphy

Project Code and Live Demo:

You can access all the project code on my GitHub repository. Additionally, explore the live demo to interact with the finished projects.

What is an Image Slider?

An image slider is a type of slideshow that displays a series of images in a horizontal or vertical arrangement. The images are displayed one after another, with a transition effect between each image. The images can be cycled through, and the user can navigate through the images using a set of navigation controls.

Other configurations can also be added to the slider like autoplay, pause on hover, zoom in and out, etc. But in this article, we will only focus on the basic configuration of the slider. And as a bonus, we will add a modal to the slider which will display the image in full size.

There are a number of image slider libraries out there that you can use to build an image slider. But in this article, we are going to build one from scratch using vanilla JavaScript. We will also be using minimal CSS to style our slider.

Building an image slider from scratch will help us understand how it works and also help us to be able to customize it to our taste. It will also help us to be able to build one from scratch without having to rely on a library.

How to Build an Image Slider with Html, CSS and JavaScript

We are going to build a simple image slider that displays a set of images one at a time. The user will be able to navigate between images using next and previous buttons. We will also add a paragraph to display the current image number and total image number.

Going into our favourite code editor, (I will be using VsCode), create 3 files called index.html, style.css and script.js, and a folder called img which will hold our images. (You can find all the images used in this tutorial here.) Now in your index.html file, copy the following code:

html
<!--* slider cntr -->
<div class="slider">
<!-- image -->
<img
class="slide-image"
src="./img/01-living-room-blue-theme.jpg"
alt="slide"
/>
<!-- the count and number of the images -->
<p>
<span class="slide-image-number">1</span> of
<span class="total-image-number">4</span>
</p>
<!-- previous btn -->
<div class="btn backward">
<span class="material-icons-outlined"> chevron_left </span>
</div>
<!-- next btn -->
<div class="btn forward">
<span class="material-icons-outlined"> chevron_right </span>
</div>
</div>

From the code above you can see that we have created a container called slider and inside it we have created an image called slide-image and a paragraph with two spans. We also created a previous button called backward and a next button called forward.

In our paragraph, the first span called slide-image-number will display the number or position of the image that is currently being displayed and the second span called total-image-number will display the total number of images that are in the slider.

The previous and next buttons as the name suggests are used to navigate back and forth through the images. I am using Google icons for the buttons. You can check it out here.

Viewed in the browser, our slider looks like this:

Image slider built with only Html

The image slider with only Html

Now let's add some styling to it. In our style.css file, copy the following code:

css
/* heading */
h3 {
text-align: center;
}
/* slider container */
.slider {
padding: 20px;
background-color: rgba(255, 255, 255, 0.2);
position: relative;
margin: 40px auto;
max-width: 600px;
}
/* image */
.slide-image {
width: 100%;
min-height: 200px;
height: auto;
max-height: 400px;
padding: 10px;
margin: 0 auto;
}
/* paragraph holding the count and number of the images */
p {
text-align: center;
}
/* prev and next btns */
.btn {
position: absolute;
top: 50%;
font-size: 80%;
background-color: rgb(228, 231, 231);
border: solid 1px rgb(201, 199, 199);
padding: 5px;
cursor: pointer;
}
/* prev btn */
.backward {
left: 0px;
}
/* next btn */
.forward {
right: 0px;
}

It should now look like this:

Image slider built with Html and CSS

Image slider with CSS stylings added to it

At the moment, our slider is only showing one image. To add more images to the slider and be able to navigate through the images, we need to do that dynamically using JavaScript. So let's add some JavaScript to our script.js file.

js
// the variables of the image slider
const image = document.querySelector(".slide-image");
const imageNumber = document.querySelector(".slide-image-number");
const totalImageNumber = document.querySelector(".total-image-number");
const prevBtn = document.querySelector(".backward");
const nextBtn = document.querySelector(".forward");
// the image array
const images = [
"./img/01-living-room-blue-theme.jpg",
"./img/02-living-room-couch.jpg",
"./img/03-living-room-red-theme.jpg",
"./img/04-modern-kitchen.jpg",
];
// the index of the image on page load
let currentImage = 0;
// the image details that shows when the webpage loads
window.addEventListener("DOMContentLoaded", showImage);
// function to select and change the image details
function showImage() {
image.src = images[currentImage];
imageNumber.textContent = currentImage + 1;
totalImageNumber.textContent = images.length;
}

We created variables called image, imageNumber, totalImageNumber, prevBtn and nextBtn. We also created an array called images which will hold all the images that we want to display in the slider.

Next, we created a variable called currentImage which will hold the index of the image in the array that is currently being displayed. This index will change when we click on our previous and next buttons which in turn changes the image that is being viewed as you will soon see.

We then wrote a function called showImage that sets our image src to be the first on the list in the array using currentImage which is initially equal to 0. We also set the contents of both the imageNumber and the totalImageNumber to be 1 and 4 which is the total number of images in the array respectively.

We then added an event listener to the window which will run the function showImage when the webpage loads. Thus, letting the user view the first image in the array.

To confirm that our javascript code is working, let's go back into our index.html file and remove the values from our img src and spans.

html
<div class="slider">
<!-- image -->
<img class="slide-image" src="" alt="slide" />
<!-- the count and number of the images -->
<p>
<span class="slide-image-number"></span> of
<span class="total-image-number"></span>
</p>
...
</div>

Refreshing the browser, our slider still looks the same.

Image slider built with HTML, CSS and JavaScript

Our slider still looks the same

Let's add some functionality to our buttons.

js
// the next button function
nextBtn.addEventListener("click", function () {
currentImage++;
if (currentImage > images.length - 1) {
currentImage = 0;
}
showImage(currentImage);
});
// the prev button function
prevBtn.addEventListener("click", function () {
currentImage--;
if (currentImage < 0) {
currentImage = images.length - 1;
}
showImage(currentImage);
});

On our next button, we added an event listener called click and added a function which sets the currentImage value to the index of the next image.

We, first of all, increase the value of currentImage by 1 using the ++ operator. Then we check if the value of currentImage is greater than the length of the array minus 1. If it is, we set the value of currentImage to 0. If it isn't, we leave it as it is. This is because we want to loop back to the first image in the array. We then call the function showImage with the currentImage value as an argument. This will display the next image in the array.

On our previous button, we added an event listener called click and added a function which sets the currentImage value to the index of the previous image.

We first of all decrease the value of currentImage by 1 using the -- operator. Then we check if the value of currentImage is less than 0. If it is, we set the value of currentImage to the length of the array minus 1. If it isn't, we leave it as it is. This is because we want to loop back to the last image in the array. We then call the function showImage with the currentImage value as an argument. This will display the previous image in the array.

Going back to our browser, let's see if our navigation buttons are working.

Vanilla js image slider built with HTML, CSS and JavaScript

The images are changing when we click on the navigation buttons

Our buttons are now working and as you can see, we have built a slider that can display images in a slideshow and can also navigate through the images using the previous and next buttons.

Remember I said at the beginning of the article that I will be adding a bonus part to this article. We have come to that part. Yes, I am also going to add a modal to the slider. So that when the user clicks on any image, a modal will appear with the image that was clicked on. and the user will still be able to navigate through the images. Let's continue with the bonus part.

Adding a Modal to an Image Slider

It's quite simple really, and we can do it in a couple of lines of code along with some reusable code. First let's add a modal to our slider in our index.html file.

html
<!--* modal -->
<div class="modal">
<span class="close-modal material-icons-outlined"> close </span>
<!-- modal content -->
<div class="modal-content">
<!--* slider cntr -->
<div class="slider">
<!-- image -->
<img class="slide-image" src="" alt="" />
<!-- the count and number of the images -->
<p>
<span class="slide-image-number"></span> of
<span class="total-image-number"></span>
</p>
<!-- previous btn -->
<div class="btn backward">
<span class="material-icons-outlined"> chevron_left </span>
</div>
<!-- next btn -->
<div class="btn forward">
<span class="material-icons-outlined"> chevron_right </span>
</div>
</div>
</div>
</div>

From the code above, we can see that we created a container called modal. We also created a container called modal-content which will hold our slider. We then duplicated the slider container into the modal content container. A span called close-modal was also added to be used to close the modal. Let's add some CSS to style our modal and its content.

css
/** modal */
.modal {
position: fixed;
top: 0;
bottom: 0;
left: 0;
right: 0;
background-color: rgba(0, 0, 0, 0.649);
display: none;
justify-content: center;
align-items: center;
z-index: 10;
}
/* close modal btn */
.close-modal {
position: absolute;
top: 10px;
right: 10px;
background-color: #fff;
}
/* modal content */
.modal-content {
width: 100vw;
}
/* slider inside the modal */
.modal-content > .slider {
max-width: initial;
background-color: transparent;
}
.modal-content > .slider > .slide-image {
width: 100%;
max-width: 800px;
display: block;
min-height: initial;
max-height: 500px;
height: auto;
}
/* paragraph holding the count and number of the images in the slider */
.modal-content p {
color: #fff;
}

Currently, our modal is not visible. We have to write some Javascript code to make it visible. We also need to refactor our code to accommodate the modal.

Refactoring our variables

js
// the variables of the image slider
const image = document.querySelectorAll(".slide-image");
const imageNumber = document.querySelectorAll(".slide-image-number");
const totalImageNumber = document.querySelectorAll(".total-image-number");
const prevBtn = document.querySelectorAll(".backward");
const nextBtn = document.querySelectorAll(".forward");
const modal = document.querySelector(".modal");
const closeBtn = document.querySelector(".close-modal");

We refactored our image, imageNumber, totalImageNumber, prevBtn, nextBtn, using querySelectorAll instead of querySelector. This is so that we can also target them in our modal content container also. We also added a variable called modal which is the modal container. And a variable called closeBtn which is the close modal button.

Refactoring our showImage function

js
// function to select and change the image details
function showImage() {
for (i of image) {
i.src = images[currentImage];
i.addEventListener("click", function () {
modal.style.display = "flex";
});
}
for (i of imageNumber) {
i.textContent = currentImage + 1;
}
for (i of totalImageNumber) {
i.textContent = images.length;
}
}

We also refactored our showImage function. We added a for loop to loop through all the images. An event listener was also added to each image so that when the user clicks on an image, we display the modal.

A for loop was also added to loop through all the image numbers and the total image numbers so as to set the correct image number and total image number on both sliders.

Therefore, when the function is called, it not only runs on our image slider, it runs on the slider inside the modal as well.

Let's refactor our navigation buttons.

Refactoring our previous and next button functions

js
// the next button function
for (i of nextBtn) {
i.addEventListener("click", function () {
currentImage++;
if (currentImage > images.length - 1) {
currentImage = 0;
}
showImage(currentImage);
});
}
// the prev button function
for (i of prevBtn) {
i.addEventListener("click", function () {
currentImage++;
if (currentImage > images.length - 1) {
currentImage = 0;
}
showImage(currentImage);
});
}

So the for loop is also added to loop through all the next buttons and the prev buttons. And the event listener is added to each button.

Let's write some more code to close the modal.

js
// close the modal
closeBtn.addEventListener("click", function () {
modal.style.display = "none";
});

An event listener is added to the close modal button. When the user clicks on the button, the modal will be closed.

Now let's test our code.

An image slider built with HTML, CSS and JavaScript with a modal that opens when you click on any of the images

When we click on any of the images, the modal is displayed with the image that was clicked on

Everything is working fine. Yay!

Our image slider is working perfectly along with the navigation buttons. When we click on any of the images, the modal will be displayed with the enlarged image that was currently clicked on. We can also navigate through the images using the next and prev buttons as well.

We can also close the modal by clicking on the close modal button. When we close the modal, the image slider will be back to its original state showing the image that we were currently on before closing the modal.

Conclusion

  • We have seen how easy it is to build an image slider built with minimal CSS and vanilla Javascript code.

  • We also added simple navigation buttons to help us navigate through the images and added a paragraph to display the current image number and total image number.

  • We also saw how easy it is to create a modal that can be opened by clicking on any of the images and can be closed by clicking on the close modal button.

  • We also made the images in the slider and modal correspond to each other irrespective of each other or where they are being viewed.

  • We not only learnt how to build a slider, we learnt how to build a modal as well.

And that's the end of this tutorial. I hope you liked it. If you have any questions or comments, please feel free to send me a dm or contact me via the links below.

Till next time guys, Byeee!

man smiling and waving goodbye

Image by

GIPHY

Resources

Connect With Me

Follow me on X(Twitter), and LinkedIn to stay updated with my latest content.

If you like my notes and want to support me, you can sponsor me on GitHub Sponsor, or you can buy me a virtual ice cream on ByMeACoffee or Selar. I would really appreciate it. 🙏

For other ways to support me, visit my Sponsorship page or Affiliate Links page.

Frequently Asked Questions

1. What is an image slider?

An image slider is a type of slideshow that displays a series of images in a horizontal or vertical arrangement. The images are shown one after another with transition effects between each image. Image sliders are commonly used on websites to showcase multiple images in a visually appealing manner.

2. What is Vertical Slider in JavaScript?

A vertical slider in JavaScript refers to an image slider or carousel that displays images in a vertical orientation, allowing users to navigate through the images by moving them up or down. This is achieved through JavaScript programming to handle the transition and user interactions for the vertical slider.

3. Why is my Swiper JS grid not working?

There could be various reasons why your Swiper JS grid is not working. Check if you have correctly implemented the Swiper JS library, and ensure that your HTML and JavaScript code is set up properly. Verify that the Swiper container and grid elements are structured correctly and that there are no errors in the console. Additionally, make sure you have the latest version of Swiper JS and consult the documentation for troubleshooting.

4. What is a JavaScript slideshow?

A JavaScript slideshow is a dynamic presentation of images or content that automatically transitions between slides. It is created using JavaScript to control the timing and animation of the slides. JavaScript slideshows are commonly used on websites to highlight multiple images or pieces of information in a sequential manner.

5. Are there image slider libraries?

Yes, there are several image slider libraries available. Some popular ones include SwiperJs, Slick, Glide, and Flickity. These libraries provide pre-built components and functionalities to easily implement and customize image sliders on websites. Choosing a library depends on your specific requirements and design preferences.

6. How to create a slider in JavaScript?

To create a slider in JavaScript, you can follow these general steps:

  • Create HTML structure for the slider, including container, images, and navigation buttons.
  • Add CSS styles for layout and appearance.
  • Use JavaScript to handle user interactions and manage image transitions.
  • Implement functions for next and previous buttons to navigate through the images.
  • Optional: Enhance the slider with additional features like autoplay, pause on hover, etc.
Additionally, you can use third-party libraries like Swiper or Slick for a more streamlined implementation.

7. How can I add autoplay to my JavaScript image slider?

To add autoplay to your JavaScript image slider, you can use the setInterval() function in JavaScript to automatically trigger the transition to the next image at regular intervals. Create a function that updates the current image index and calls the showImage function. Start the autoplay when the page loads, and you can also include controls to pause or resume the autoplay based on user interactions.

8. What are some best practices for optimizing image sliders for performance?

Optimizing image sliders for performance involves several best practices. Use appropriately sized images to reduce loading times, implement lazy loading to load images only when they are about to be displayed, minimize the use of large image files, and utilize responsive design to ensure a seamless experience on various devices. Additionally, consider optimizing JavaScript code for efficient image transitions and minimize unnecessary animations.

9. Can I integrate a JavaScript image slider with a content management system (CMS) like WordPress?

Yes, you can integrate a JavaScript image slider with CMS platforms like WordPress. One common approach is to create a custom HTML, CSS, and JavaScript slider and then embed it within WordPress pages or posts. Alternatively, you can explore WordPress plugins that provide customizable sliders, or you can develop a custom WordPress theme with integrated slider functionality.

10. How do I handle responsive design in a JavaScript image slider?

Handling responsive design in a JavaScript image slider involves ensuring that the slider adapts to different screen sizes and devices. Use CSS media queries to adjust the layout and styling based on the screen width. Additionally, make sure that the JavaScript code accounts for changes in dimensions and provides a seamless user experience across various devices, such as smartphones, tablets, and desktops.

Subscribe to my newsletter 💌

Never miss a beat! Stay updated with my latest tech tutorials, code snippets, how-to guides, productivity tips, personal projects and experiences, and more! 💻📚✨