w3resource

JavaScript Slideshow - Next & previous button image change

JavaScript Event Handling: Exercise-5 with Solution

Image Slideshow Navigation

Write a JavaScript program to create a slideshow that changes the displayed image when a next or previous button is clicked.

Sample Solution:

HTML and JavaScript Code:

<!DOCTYPE html>
<html>
<head>
  <style>
    .slideshow {
      display: flex;
      justify-content: center;
      align-items: center;
      height: 300px;
    }

    .slideshow img {
      width: 300px;
      height: 300px;
    }
  </style>
</head>
<body>
  <div class="slideshow">
    <button id="previousBtn">Previous</button>
    <img id="image" src="image1.jpg">
    <button id="nextBtn">Next</button>
  </div>

  <script>
    const images = ['image1.jpg', 'image2.jpg', 'image3.jpg'];
    let currentIndex = 0;

    const previousBtn = document.getElementById('previousBtn');
    const nextBtn = document.getElementById('nextBtn');
    const image = document.getElementById('image');

    previousBtn.addEventListener('click', () => {
      currentIndex = (currentIndex - 1 + images.length) % images.length;
      image.src = images[currentIndex];
    });

    nextBtn.addEventListener('click', () => {
      currentIndex = (currentIndex + 1) % images.length;
      image.src = images[currentIndex];
    });
  </script>
</body>
</html>

Output:

JavaScript Slideshow - Next & previous button image change.

Note: Executed on JS Bin

Flowchart:

Flowchart: JavaScript Slideshow - Next & previous button image change.

Live Demo:

See the Pen javascript-event-handling-exercise-5 by w3resource (@w3resource) on CodePen.


For more Practice: Solve these Related Problems:

  • Write a JavaScript program that implements a slideshow with next and previous buttons using fade transitions between images.
  • Write a JavaScript function that creates an infinitely looping image slideshow with navigation buttons that wrap around.
  • Write a JavaScript program that adds keyboard navigation (left/right arrow keys) to control the image slideshow.
  • Write a JavaScript function that automatically advances the slideshow at set intervals and pauses on mouse hover.

Go to:


PREV : Form Validation with Error Message.
NEXT : Drag-and-Drop List Reordering.

Improve this sample solution and post your code through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.