JavaScript Custom Image Slider



An image slider is a user interface component in JavaScript that allows users to view a series of images in a slideshow format. It is also known as a carousel or slideshow. An image slider consists of navigation buttons (such as next and previous buttons) that allow users to navigate from one image to the other.

With the help of basic HTML for structuring and CSS for designing or making the image slider presentable, along with simple JavaScript logic, you can create an image slider efficiently. This article will guide you through creating a basic image slider with navigation buttons.

Prerequisites For Image Slider

The creation of a custom image slider just needs a basic understanding and knowledge of the following.

  • HTML: The basic understanding of the structure of HTML document and familiarity with elements such as <div>, <img> is needed.
  • CSS: You need to know CSS to style the slider, including its layout, colors, fonts, and transitions. Understanding how to use positioning methods like flexbox or grid is also important for arranging the images and controls.
  • JavaScript: You should have a basic understanding of JavaScript to make the slider interactive and know how to manipulate the DOM to change images and respond to user actions, like clicks.

Implementation Steps

To create a custom image slider, follow the steps mentioned below:

  • HTML and CSS Code: Create a basic image slider container using html and style it with css based on requirements.
  • Add Event Listeners to Navigation Buttons:
    • Select Navigation Buttons: Use document.querySelector() to select the previous and next buttons.
    • Attach Click Events: Add event listeners to the buttons to call functions when clicked: use changeSlides(-1) for the previous button and changeSlides(1) for the next button.
  • Initialize Slide Index and Display Initial Slide:
    • Initialize Slide Index: Set slideIndex to 1 to start with the first slide.
    • Display Initial Slide: Call showSlides(slideIndex) to display the first slide.
  • Implement Slide Logic:
    • Change Slides Function: The changeSlides(n) function updates the slide index and then calls showSlides(), which moves to the next or previous slide.
    • Current Slide Function: The currentSlide(n) function sets the slide index to a specific value and calls showSlides(), which is used when clicking on navigation dots.
    • Show Slides Function: The showSlides(n) function displays the slides and updates the navigation dots while keeping the slide index within bounds. It hides all slides, removes the "selected" class from all dots, then shows the slide at the current index and adds the "selected" class to the corresponding dot.
  • Finalize Navigation Dots
    • Add Click Events to Dots: In the HTML, each dot should have an onclick attribute calling currentSlide(n) with its corresponding slide number.
    • Test Navigation: Ensure clicking on dots correctly changes the slide.
  • Test the Slider: Then, test the slider working properly.

Code Implementation

The following is a simple code of creating a custom image slider in JavaScript along with HTML and CSS.

<!DOCTYPE html>
<html>
<head>
<style>
    * {
        box-sizing: border-box;
    }
    .Slide {
        display: none;
    }
    img {
        vertical-align: middle;
        width: 100%;
        height: 400px;
    }
    .slideContainer {
        max-width: 600px;
        position: relative;
        margin: auto;
    }
    .prevBtn,
    .nextBtn {
        position: absolute;
        top: 50%;
        width: auto;
        padding: 10px;
        background-color: rgb(255, 255, 75);
        color: rgb(50, 0, 116);
        font-weight: bolder;
        font-size: 18px;
    }
    .nextBtn {
        right: 0;
    }
    .Caption {
        color: #fbff09;
        font-weight: bold;
        font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
        font-size: 25px;
        padding: 8px 12px;
        position: absolute;
        bottom: 8px;
        width: 100%;
        text-align: center;
    }
    .Navdot {
        cursor: pointer;
        height: 15px;
        width: 15px;
        margin: 0 2px;
        background-color: rgb(54, 5, 117);
        border-radius: 50%;
        display: inline-block;
        transition: background-color 0.6s ease;
    }
    .selected,
    .Navdot:hover {
        background-color: #d9ff00;
    }
    @media only screen and (max-width: 450px) {
        .prevBtn,
        .nextBtn,
        .Caption {
            font-size: 16px;
        }
    }
</style>
</head>
<body>
<div class="slideContainer">
<div class="Slide">
<img src="https://images.pexels.com/photos/3540375/pexels-photo-3540375.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=650&w=940" />
<div class="Caption">Photo 1</div>
</div>
<div class="Slide">
<img src="https://images.unsplash.com/photo-1558981001-5864b3250a69?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=750&q=80" />
<div class="Caption">Photo 2</div>
</div>
<div class="Slide">
<img src="https://images.unsplash.com/photo-1584910758141-f7993f9e203d?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=667&q=80" />
<div class="Caption">Photo 3</div>
</div>
<a class="prevBtn">?</a>
<a class="nextBtn">?</a>
</div>
<br />
<div style="text-align:center">
<span class="Navdot" onclick="currentSlide(1)"></span>
<span class="Navdot" onclick="currentSlide(2)"></span>
<span class="Navdot" onclick="currentSlide(3)"></span>
</div>
<script>
    document.querySelector(".prevBtn").addEventListener("click", () => {
        changeSlides(-1);
    });
    document.querySelector(".nextBtn").addEventListener("click", () => {
        changeSlides(1);
    });
    var slideIndex = 1;
    showSlides(slideIndex);
    function changeSlides(n) {
        showSlides((slideIndex += n));
    }
    function currentSlide(n) {
        showSlides((slideIndex = n));
    }
    function showSlides(n) {
        var i;
        var slides = document.getElementsByClassName("Slide");
        var dots = document.getElementsByClassName("Navdot");
        if (n > slides.length) {
            slideIndex = 1;
        }
        if (n < 1) {
            slideIndex = slides.length;
        }
        Array.from(slides).forEach(item => (item.style.display = "none"));
        Array.from(dots).forEach(
            item => (item.className = item.className.replace(" selected", ""))
        );
        slides[slideIndex - 1].style.display = "block";
        dots[slideIndex - 1].className += " selected";
    }
</script>
</body>
</html>

Output


Conclusion

In this article, we have seen how to create a custom image slider. We have used simple HTML, CSS, and JavaScript for creating this. This method is great for small projects or when you want to keep things simple without using external libraries.

Updated on: 2025-04-24T16:44:12+05:30

860 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements