DEV Community

Cover image for Day-5 of Learning JavaScript: Unveiling Elegance: Building an Image Slider with JavaScript Prowess
Aniket Saini
Aniket Saini

Posted on

Day-5 of Learning JavaScript: Unveiling Elegance: Building an Image Slider with JavaScript Prowess

Greetings, fellow creators of the digital canvas! Today, let’s embark on a journey to create a simple yet enchanting image slider — a captivating showcase that allows users to gracefully navigate through a curated set of images. Guided by the magic wand of JavaScript, we’ll orchestrate seamless transitions, breathing life into our static images.

Chapter 1: The Blank Canvas in HTML

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Magic Image Slider</title>
    <link rel="stylesheet" href="styles.css"> <!-- Link to our style sheet -->
</head>
<body>
    <div id="slider-container">
        <!-- The enchanted display for our images -->
        <div id="image-display">
            <!-- Images will be dynamically added here -->
        </div>

        <!-- The navigation buttons -->
        <button id="prev-button">&lt;</button>
        <button id="next-button">&gt;</button>
    </div>
    <script src="script.js"></script> <!-- Our JavaScript spellbook -->
</body>
</html>
Enter fullscreen mode Exit fullscreen mode

In this HTML spell, we have a div with the id “slider-container” as our mystical realm. The display div inside is where our images shall manifest, and the buttons, well, they are our navigation wands.


Chapter 2: The Aesthetic Elegance — Styling with CSS

Before we delve into the magical realm of JavaScript, let’s add a touch of style to our image slider. Open the styles.css file:

/* styles.css */

#image-container {
    position: relative;
    width: 100%;
    height: 100vh;
    display: flex;
    justify-content: center;
    align-items: center;
}

#current-image {
    max-width: 80%;
    max-height: 80%;
}

button {
    position: absolute;
    top: 50%;
    transform: translateY(-50%);
    font-size: 24px;
    background-color: #000;
    border: 1px solid #ccc;
    padding: 10px;
    cursor: pointer;
    color: white;
    border-radius: 10px;
}

#prev-button {
    left: 50px;
}

#next-button {
    right: 50px;
}
Enter fullscreen mode Exit fullscreen mode

This CSS enchantment adds visual charm to our image slider. The container gets a fixed width, and images will gracefully transition with a subtle ease effect. The navigation buttons are positioned on either side for a seamless user experience.


Chapter 3: The JavaScript Alchemy

// script.js

// Our magical spellbook begins

const currentImage = document.getElementById('current-image');
const prevButton = document.getElementById('prev-button');
const nextButton = document.getElementById('next-button');

let currentIndex = 0;
const images = [
    'https://picsum.photos/id/1015/600/400',
    'https://picsum.photos/id/1016/600/400',
    'https://picsum.photos/id/1018/600/400',
    'https://picsum.photos/id/1020/600/400',
    // Add more images as needed
];

function updateImage() {
    currentImage.src = images[currentIndex];
  imageContainer.style.transform = `translateX(-${currentIndex * 100}%)`;
}

prevButton.addEventListener('click', () => {
    currentIndex = (currentIndex - 1 + images.length) % images.length;
    updateImage();
});

nextButton.addEventListener('click', () => {
    currentIndex = (currentIndex + 1) % images.length;
    updateImage();
});

updateImage();
Enter fullscreen mode Exit fullscreen mode

This JavaScript spellbook orchestrates the dance of images. Let’s decipher the magic:

  • currentImage, prevButton, and nextButton are variables that store references to the HTML elements with corresponding IDs.

  • currentIndex is a variable that keeps track of the currently displayed image index.

  • The images array contains URLs of the images to be displayed.

  • The updateImage function sets the src attribute of the currentImage element to the URL of the current image and updates the transform property of the imageContainer to shift the images horizontally based on the current index.

  • Event listeners are added to the previous and next buttons. When clicked, they update the currentIndex and call updateImage to display the corresponding image.

  • Finally, the updateImage function is called to initially display the first image.


JavaScript Concepts Learned:

  • DOM Manipulation: The code uses the DOM API to access and manipulate HTML elements.

  • Event Handling: Event listeners are added to respond to button clicks, triggering the navigation through the images.

  • Arrays: The images array stores URLs, and the currentIndex variable is used to access and update elements in the array.

  • Arrow Functions: Arrow functions are used for the event listener callbacks.

CLICK HERE to check the Final Output


The Grand Finale

Open your enchanted HTML page in a browser. Witness the magic as you gracefully navigate through the array of images using the charming buttons

🌟 Don’t be a stranger! If you’ve found this spellbinding experience amusing or if you have secrets to share from your own coding adventures, drop a like and sprinkle some comments below. Your magical words are like potions that make the code spirits dance!

🚀 Spread the enchantment! Share this magical scroll with your fellow sorcerers and apprentices. Let them experience the joy of weaving spells with JavaScript and diving into the world of image sorcery.

🧙‍♂️ Join the Fellowship of the Code! Follow me to stay tuned for more magical concoctions. Together, we’ll explore the depths of the coding cauldron and unravel the secrets of the digital realm.

May your code be bug-free and your spells forever enchanting! ✨🔮

Top comments (0)