Sling Academy
Home/JavaScript/Dynamic Image Galleries: Changing src on the Fly in JavaScript

Dynamic Image Galleries: Changing src on the Fly in JavaScript

Last updated: December 10, 2024

Creating an interactive image gallery is a common task in web development. By leveraging JavaScript, we can enhance user experience by dynamically changing the source of images, making galleries more flexible and attractive. This tutorial will guide you through building a basic image gallery where clicking on thumbnails will change the displayed main image.

Setting Up Your HTML Structure

Start by laying out the basic HTML structure for the gallery. You'll need a container for the main image and a series of thumbnail images. Here's a simple setup:

<div class="image-gallery">
  <img id="main-image" src="images/default.jpg" alt="Main Image">
  <div class="thumbnails">
    <img class="thumb" src="images/thumb1.jpg" data-large="images/large1.jpg" alt="Thumbnail 1">
    <img class="thumb" src="images/thumb2.jpg" data-large="images/large2.jpg" alt="Thumbnail 2">
    <img class="thumb" src="images/thumb3.jpg" data-large="images/large3.jpg" alt="Thumbnail 3">
  </div>
</div>

Here, we use data-large attributes to store the URLs of the larger images. This practice keeps the main source light, and when you need the full-sized image, you can quickly fetch it using JavaScript.

Adding Some Basic Styling

Let's add a bit of CSS to make the gallery visually appealing:

.image-gallery {
  text-align: center;
}

.main-image {
  width: 500px;
  height: auto;
  margin-bottom: 20px;
}

.thumbnails .thumb {
  width: 100px;
  height: auto;
  cursor: pointer;
  transition: transform 0.2s;
}

.thumbnails .thumb:hover {
  transform: scale(1.1);
}

These styles ensure that the main image is displayed prominently, and that the thumbnails are identifiable and responsive to user actions.

Introducing JavaScript to Handle Image Change

Now, let's implement the JavaScript logic to swap the main image when a thumbnail is clicked:

document.addEventListener('DOMContentLoaded', function() {
  const mainImage = document.getElementById('main-image');
  const thumbnails = document.querySelectorAll('.thumb');

  thumbnails.forEach(thumb => {
    thumb.addEventListener('click', function() {
      const largeImageSrc = this.dataset.large;
      mainImage.src = largeImageSrc;
    });
  });
});

This script adds an event listener to each thumbnail that changes the source of the main image to that of the corresponding large image when clicked.

Testing and Debugging

Once your gallery is set up, test it by clicking on the thumbnails. Ensure that each one displays the correct main image. If something doesn’t work as expected, check that:

  • The data-large attribute is set correctly in each thumbnail.
  • No typos exist in your JavaScript affecting query selectors or DOM manipulation.

There are numerous ways to enhance this basic setup:

  • Adding image preload hints to improve loading times for large images.
  • Incorporating animations to smoothly transition between images.
  • Including caption or image descriptions that change dynamically with the image.
  • Integrating a lightbox effect to view images in a larger format.

By following these steps, you can create a responsive and dynamic image gallery that caters to user interaction intuitively and efficiently.

Next Article: Replacing Content with JavaScript: Using replaceChild()

Previous Article: Hover Effects with JavaScript: No CSS? No Problem!

Series: JavaScript: Document Object Model Tutorials

JavaScript

You May Also Like

  • Handle Zoom and Scroll with the Visual Viewport API in JavaScript
  • Improve Security Posture Using JavaScript Trusted Types
  • Allow Seamless Device Switching Using JavaScript Remote Playback
  • Update Content Proactively with the JavaScript Push API
  • Simplify Tooltip and Dropdown Creation via JavaScript Popover API
  • Improve User Experience Through Performance Metrics in JavaScript
  • Coordinate Workers Using Channel Messaging in JavaScript
  • Exchange Data Between Iframes Using Channel Messaging in JavaScript
  • Manipulating Time Zones in JavaScript Without Libraries
  • Solving Simple Algebraic Equations Using JavaScript Math Functions
  • Emulating Traditional OOP Constructs with JavaScript Classes
  • Smoothing Out User Flows: Focus Management Techniques in JavaScript
  • Creating Dynamic Timers and Counters with JavaScript
  • Implement Old-School Data Fetching Using JavaScript XMLHttpRequest
  • Load Dynamic Content Without Reloading via XMLHttpRequest in JavaScript
  • Manage Error Handling and Timeouts Using XMLHttpRequest in JavaScript
  • Handle XML and JSON Responses via JavaScript XMLHttpRequest
  • Make AJAX Requests with XMLHttpRequest in JavaScript
  • Customize Subtitle Styling Using JavaScript WebVTT Integration