Geekflare is supported by our audience. We may earn affiliate commissions from buying links on this site.
Share on:

How to Create Image Slider with JavaScript to Amp Up Your Website

How to Create Image Slider with JavaScript to Amp Up Your Website
Invicti Web Application Security Scanner – the only solution that delivers automatic verification of vulnerabilities with Proof-Based Scanning™.

Have you ever found yourself in a situation where you want to display several images/ videos on a section of a web page but don’t want to occupy a lot of space? Do you want to add interactivity to your web pages or make them more attractive?

An image slider can save you the struggle. In this article, we will define an image slider, the prerequisites of creating an image slider, and how to create one using HTML, JavaScript, and CSS. 

What is an Image Slider?

What-is-an-Image-Slider

Sliders are carousels or slideshows that display texts, images, or videos. This article will focus on image sliders. Most web developers use sliders on the homepage to showcase to promote offers or the most important information. 

These are some reasons you should use sliders on your web pages. 

  • Improve user experience: An ideal webpage should be compact so end-users don’t have to scroll and scroll to get important data. If you have multiple images, you can save users the hassle of scrolling by displaying them in a slider. 
  • Visual appeal: Most website users will not spend much time on a plain web page. You can improve the visual appeal with sliders and animations. 
  • Save space: If you have like 20 images you want to display on your web page, they may take up a lot of space. Creating a slider will allow you to save space and still allow users to access all of them. 
  • Display dynamic content: You can use sliders to display dynamic content such as social media embeds, blogs, and news. 

Prerequisites for Creating an Image Slider

  • A basic understanding of HTML: We shall describe the slider’s structure here. You should be comfortable working with various HTML tags, classes, and divs. 
  • A basic understanding of CSS: We shall use CSS to style our image sliders and buttons.
  • A basic understanding of JavaScript: We shall use JavaScript to make the image sliders responsive.
  • A code editor: You can use your code editor of choice. I will be using Visual Studio Code
  • A collection of images.

Set up the project folder

We need a project folder, an images folder inside it, and HTML, CSS, and JavaScript files. I will name my project “Image-Slider”. You can create your project manually or use these commands to get started;

mkdir Image-Slider

cd Image-Slider

mkdir Images && touch index.html styles.css script.js

Add all your images to the “Images” folder we created inside the project folder and move to the next step. 

This is my project folder, where I have added six images that I will use to create a slider. All our HTML code will be in the index.html file.

Types of Image Sliders

We can have two types of Image Sliders; an automatic slider and an automatic image slider with buttons.

#1. Automatic Image Slider

An automatic slider scrolls to the next image automatically after a given time, say, for instance, 3 seconds.

HTML code 

This is my 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">
    <title>Document</title>
    <link rel="stylesheet" href="styles.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.3/css/all.min.css" />


</head>

<body>
  <div id="slider">
    <div class="slide">
        <h1>African</h1>
      <img src="Images/img1.jpg" alt="Image 1">
    </div>
    <div class="slide">
        <h1>American</h1>
      <img src="Images/img2.jpg" alt="Image 2">
    </div>
    <div class="slide">
        <h1>Asian</h1>
      <img src="Images/img3.jpg" alt="Image 3">
    </div>
    <div class="slide">
        <h1>Arabic</h1>
      <img src="Images/img4.jpg" alt="Image 4">
    </div>
    <div class="slide">
        <h1>Modern </h1>
      <img src="Images/img5.jpg" alt="Image 5">
    </div>
    <div class="slide">
        <h1> European </h1>
      <img src="Images/img6.jpg" alt="Image 6">
    </div>
  </div>

  <script src="script.js"></script>


</body>
</html>

From this code, we can note the following;

  • I have imported my CSS file to index.html in the <head> section. This will be used in later steps. 

  <link rel="stylesheet" href="styles.css">

  • I have added JavaScript to my HTML code just before the closing <body> tag. I will use JavaScript to add functionality to the sliders. 
  • Every slide has a class of slide.
  • I have used the <img> tag to import images from the Images folder. 

Style the automatic image slider using CSS

We can now style our images since we have already linked CSS and HTML files. 

Add this code to your CSS file;

#slider {
    width: 80%;
  }
  
  .slide {
    width: 80%;
    display: none;
    position: relative;
  }
  
  .slide img {
    width: 80%;
    height: 80%;
  }
  
  .slide.active {
    display: block;
  }

From this code, we can note the following;

  • We have the width and height of our slider to 80%
  • We have set the active slide to block, meaning only the active slide will be displayed while the rest are hidden.

How to add JavaScript to make the image slider responsive

Add this code to your script.js file;

var slides = document.querySelectorAll('.slide');
var currentSlide = 0;
var slideInterval = setInterval(nextSlide,2000);

function nextSlide() {
  slides[currentSlide].className = 'slide';
  currentSlide = (currentSlide+1)%slides.length;
  slides[currentSlide].className = 'slide active';
}

This JavaScript does the following;

  • We use document.querySelectorAll selector to target all elements with a class of slide.
  • We give the currentSlide 0 initial value.
  • We set the slideInterval as 2000 (2 seconds), meaning the images in the slider changes after every 2 seconds.
  • This code slides[currentSlide].className = 'slide'; removes active class from the current slide  
  • This code currentSlide = (currentSlide + 1) % slides.length; increments the current slide index.
  • This code slides[currentSlide].className = 'slide active'; adds active class to the current slide. 

The automatic slider works as follows;

#2. Automatic Slider with Buttons

The image slider we created auto-scrolls after every 2 seconds. We can now create an image where users can move to the next slide by clicking a button or auto-scrolls after every 3 seconds if the user does not click the buttons. 

HTML code

You can change the contents of your index.html file as follows;

<!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" />
    <title>Image Slider</title>
    <link
      rel="stylesheet"
      href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.3/css/all.min.css"
    />
    <link rel="stylesheet" href="styles.css" />
  </head>
  <body>
    <div class="container">

        <div class="mySlides">
            <img src="Images/img1.jpg" style="width:100% ; height:50vh" >
        </div>
      
        <div class="mySlides">
            <img src="Images/img2.jpg" style="width:100% ; height:50vh">
        </div>
      
        <div class="mySlides">
            <img src="Images/img3.jpg" style="width:100% ; height:50vh">
        </div>
      
        <div class="mySlides">
            <img src="Images/img4.jpg" style="width:100% ; height:50vh">
        </div>
      
        <div class="mySlides">
            <img src="Images/img5.jpg" style="width:100% ; height:50vh">
        </div>
      
      
        <a class="prev" onclick="plusSlides(-1)">❮</a>
        <a class="next" onclick="plusSlides(1)">❯</a>
      
        <div class="caption-container">
          <p id="caption"></p>
        </div>
      
        <div class="row">
          <div class="column">
            <img class="demo cursor" src="Images/img1.jpg" style="width:100%" onclick="currentSlide(1)" alt="European">
          </div>
          <div class="column">
            <img class="demo cursor" src="Images/img2.jpg" style="width:100%" onclick="currentSlide(2)" alt="African">
          </div>
          <div class="column">
            <img class="demo cursor" src="Images/img3.jpg" style="width:100%" onclick="currentSlide(3)" alt="American">
          </div>
          <div class="column">
            <img class="demo cursor" src="Images/img4.jpg" style="width:100%" onclick="currentSlide(4)" alt="Asian">
          </div>
          <div class="column">
            <img class="demo cursor" src="Images/img5.jpg" style="width:100%" onclick="currentSlide(5)" alt="Modern">
          </div>
          
        </div>
      </div>

    <script src="script.js"></script>
  </body>
</html>

This HTML code works as follows;

  • We have a class named mySlides that carries our five images.
  • We have two buttons, “prev” and “next” with an onClick, allowing users to scroll through the slides.
  • We have a thumbnail that shows the images at the bottom part of the web page.

CSS code

Add this to your code;

* {
  box-sizing: border-box;
}

.container {
  position: relative;
}

.mySlides {
  justify-content: center;
}

.cursor {
  cursor: pointer;
}

.prev,
.next {
  cursor: pointer;
  position: absolute;
  top: 40%;
  width: auto;
  padding: 16px;
  margin-top: -50px;
  color: rgb(34, 143, 85);
  font-weight: bold;
  font-size: 20px;
  border-radius: 0 3px 3px 0;
  user-select: none;
  -webkit-user-select: none;
}

.next {
  right: 0;
  border-radius: 3px 0 0 3px;
}

.prev:hover,
.next:hover {
  background-color: rgba(0, 0, 0, 0.8);
}

.caption-container {
  text-align: center;
  background-color: orangered;
  padding: 2px 16px;
  color: white;
}

.row:after {
  content: "";
  display: table;
  clear: both;
}

.column {
  float: left;
  width: 16.66%;
}

.demo {
  opacity: 0.6;
}

.active,
.demo:hover {
  opacity: 1;
}

The CSS code works as follows;

  • We have set the .mySlides class display property as none, meaning that all the slides are hidden by default. 
  • We have set the opacity of the thumbnails being hovered on as 1 through the active, .demo:hover {opacity: 1;} rule.

JavaScript code

let slideIndex = 1;
showSlides(slideIndex);

function plusSlides(n) {
  showSlides(slideIndex += n);
}

function currentSlide(n) {
  showSlides(slideIndex = n);
}

let slideInterval = setInterval(() => {
  plusSlides(1);
}, 3000);

let slideshowContainer = document.getElementsByClassName('slideshow-container')[0];
slideshowContainer.addEventListener('mouseenter', () => {
  clearInterval(slideInterval);
});

slideshowContainer.addEventListener('mouseleave', () => {
  slideInterval = setInterval(() => {
    plusSlides(1);
  }, 3000);
});

function showSlides(n) {
  let i;
  let slides = document.getElementsByClassName("mySlides");
  let dots = document.getElementsByClassName("demo");
  let captionText = document.getElementById("caption");
  if (n > slides.length) {slideIndex = 1}
  if (n < 1) {slideIndex = slides.length}
  for (i = 0; i < slides.length; i++) {
    slides[i].style.display = "none";
  }
  for (i = 0; i < dots.length; i++) {
    dots[i].className = dots[i].className.replace(" active", "");
  }
  slides[slideIndex-1].style.display = "block";
  dots[slideIndex-1].className += " active";
  captionText.innerHTML = dots[slideIndex-1].alt;
}

You can get the final source code here.

Our JavaScript code does the following; 

  • We have a currentSlide function with a display value set as none. This rule allows our web page to display only the current slide. 
  • We have a plusSlides function that adds/subtracts the given value from slideIndex to determine which slide to display. 
  • If the user does not click the buttons, the slides will auto-scroll after every 3000 milliseconds. 

If a user uses the navigation tab, our image slider will work as follows;

If the user does not use the navigation buttons, the image slider will auto-scroll after every 3 seconds as follows;

Test and Debug Image Slider

Errors and errors are part of a developer’s journey, and having them in your code does not mean you are a bad developer. If your code is not working even after following the steps mentioned above, you can try these testing and debugging options to fix errors:

  • Debug each file separately: Our code has three files, HTML, CSS, and JavaScript files. The three languages have different rules. You can check whether your HTML, CSS, and JavaScript codes are valid using tools such as W3C Markup Validation Service for HTML, CSS Validator for your CSS code, and Chrome DevTools to test your JavaScript code. 
  • Perform different test types: You can do Visual tests to ensure the images are displayed correctly, Performance tests to check whether the images are responsive and Functional tests to ensure that the images are navigable. 
  • Test your code with different image formats and sizes: A good image slider should work with different image formats and sizes.
  • Automate your tests: Automation is everywhere, and you, too, can benefit from it in testing. You can use tools like Selenium or LoadRunner to write and execute test automation scripts. These tools also allow you to reuse some of your tests. 
  • Document your tests: Testing is a continuous process. You may have to keep improving your tests until your code works as expected. Document this process to make your code readable and easy to reference. 

Image Sliders: Best Practices

  • Keep it simple: Sliders are attractive. However, keep the number of images in a slider low. Something like 4-7 images per slide is ideal. 
  • Test your sliders: Test them for functionality before publishing them online. 
  • Create responsive sliders: Ensure your created sliders are responsive to different screen sizes. 
  • Use high-quality images: Take/ download high-quality images for your sliders. Saving your images in the SVG format is an awesome approach, as they don’t lose their quality when you resize them. 
  • Resize your images: You may have different image sizes and formats. Always ensure that the images in a slider are of the same size. You can achieve this through CSS. 

Wrapping Up

We hope you can now create a fully-functional image slider to display important data on your website without using UI frameworks. You can use the same approach to create video sliders on web pages. 


Thanks to our Sponsors
More great readings on Development
Power Your Business
Some of the tools and services to help your business grow.
  • Invicti uses the Proof-Based Scanning™ to automatically verify the identified vulnerabilities and generate actionable results within just hours.
    Try Invicti
  • Web scraping, residential proxy, proxy manager, web unlocker, search engine crawler, and all you need to collect web data.
    Try Brightdata
  • Semrush is an all-in-one digital marketing solution with more than 50 tools in SEO, social media, and content marketing.
    Try Semrush
  • Intruder is an online vulnerability scanner that finds cyber security weaknesses in your infrastructure, to avoid costly data breaches.
    Try Intruder