Table of Contents
1. HTML structure: Defining the gallery skeleton
2. CSS Style: Beautification and Layout Gallery
3. JavaScript interactive logic: implement image switching function
4. Key points and precautions
Home Web Front-end HTML Tutorial Building an interactive JavaScript picture gallery: Implementing dynamic picture switching function

Building an interactive JavaScript picture gallery: Implementing dynamic picture switching function

Aug 20, 2025 pm 10:51 PM

Building an interactive JavaScript picture gallery: implement dynamic picture switching function

This tutorial details how to build a fully functional interactive picture gallery using HTML, CSS and JavaScript. We will learn how to set the structure and style of the gallery, and implement the function of dynamically switching the main image when clicking on the thumbnail. The article will cover core JavaScript logic, necessary CSS layout, and emphasize key considerations such as the correctness of image paths to help you create a picture display interface with a good user experience.

Image gallery is a common component in web design that can display multiple images in an intuitive way. An interactive gallery usually allows the user to click on the thumbnail to switch the displayed main image. This article will guide you to build such a gallery from scratch and solve common problems such as "game not interacting".

First, we need to define the HTML structure of the gallery. This includes a main image display area and a set of thumbnails.

 <div class="gallery">
  <div class="gallery-main">
    <!-- The main image display area, facilitate JavaScript operation through ID->
    <img src="/static/imghw/default1.png"  data-src="https://i.ibb.co/2kfJ15Z/image-cropped.jpg"  class="lazy" alt="main picture" id="main">
  </div>

  <div class="gallery-p">
    <!-- Thumbnail area, each thumbnail is bound to a click event -->
    <img src="/static/imghw/default1.png" data-src="https://i.ibb.co/2kfJ15Z/image-cropped.jpg" class="lazy" alt="Thumbnail 1" onclick="changeimage(this.src)">
    <img src="/static/imghw/default1.png" data-src="https://i.ibb.co/0GwkygJ/imagename-2.png" class="lazy" alt="Thumbnail 2" onclick="changeimage(this.src)">
    <img src="/static/imghw/default1.png" data-src="https://i.ibb.co/2kfJ15Z/image-cropped.jpg" class="lazy" alt="Thumbnail 3" onclick="changeimage(this.src)">
    <img src="/static/imghw/default1.png" data-src="https://i.ibb.co/0GwkygJ/imagename-2.png" class="lazy" alt="Thumbnail 4" onclick="changeimage(this.src)">
    <img src="/static/imghw/default1.png" data-src="https://i.ibb.co/2kfJ15Z/image-cropped.jpg" class="lazy" alt="Thumbnail 5" onclick="changeimage(this.src)">
    <img src="/static/imghw/default1.png" data-src="https://i.ibb.co/0GwkygJ/imagename-2.png" class="lazy" alt="Thumbnail 6" onclick="changeimage(this.src)">
  </div>
</div>

Structural description:

  • .gallery : A container for the entire gallery for overall layout and centering.
  • .gallery-main : A container containing the main image. The main image Building an interactive JavaScript picture gallery: Implementing dynamic picture switching function element has a unique id="main" so that JavaScript can accurately obtain and modify its src attributes.
  • .gallery-p : A container containing all thumbnails. Each thumbnail Building an interactive JavaScript picture gallery: Implementing dynamic picture switching function element has an inline onclick="changeimage(this.src)" event handler added. When the user clicks on a thumbnail, the global changeimage function will be called and the src attribute value of the currently clicked thumbnail is passed as a parameter this.src.

CSS is used to define the appearance and layout of a gallery, making it responsive and enhancing the visual effect.

 .gallery {
  width: 90%; /* width accounts for 90% of the parent container */
  margin: 0 auto; /* horizontal center*/
}

.gallery-main {
  width: 45rem; /* fixed width of main image area*/
  height: 30rem; /* fixed height of main image area*/
  margin: 0 auto; /* The main image area is horizontally centered*/
}

.gallery-main img {
  width: 100%; /* picture width fill container*/
  height: 100%; /* Image height fill container*/
  object-fit: cover; /* Keep the image proportion and fill the container while maintaining the size, crop the overflowing part*/
  border-radius: 8px; /* rounded border*/
  box-shadow: 0 10px 20px rgba(0, 0, 0, 0.19), 0 6px 6px rgba(0, 0, 0, 0.23); /* Shadow effect*/
}

.gallery-p {
  display: flex; /* Use Flexbox to layout thumbnails*/
  justify-content: center; /* Thumbnail center horizontally*/
  flex-wrap: wrap; /* Thumbnails are automatically wrapped to adapt to small screen*/
  margin-top: 2rem; /* Top margin*/
}

.gallery-p img {
  width: 9rem; /* Thumbnail fixed width*/
  height: 7rem; /* Thumbnail fixed height*/
  object-fit: cover; /* Keep the image proportions and fill the container*/
  border-radius: 4px; /* rounded border*/
  margin: 0.5rem; /* Spacing between thumbnails*/
  cursor: pointer; /* The hand cursor is displayed when the mouse is hovered, and you can click */
}

Style description:

  • Responsive design : width: 90%; and margin: 0 auto; to adapt and center the gallery width.
  • Image filling and cropping : object-fit: cover; Ensure that the image can be displayed correctly in containers of different sizes, avoid deformation, and fill the entire area at the same time.
  • Flexbox layout : .gallery-p Use display: flex; in conjunction with justify-content: center; and flex-wrap: wrap; to achieve centering and wrapping thumbnails, which is very important for adapting different screen sizes.
  • User experience : cursor: pointer; Improve user experience and clearly state that thumbnails are clickable elements.

3. JavaScript interactive logic: implement image switching function

JavaScript is the core of implementing gallery interaction. We define a simple function to update the src attribute of the main image based on the incoming image path.

 // Define a function to change the source of the main image const changeimage = (src) => {
  // Get the main image element through ID const mainImage = document.getElementById("main");
  // Update the src attribute of the main image to the passed src parameter mainImage.src = src;
}

Code description:

  • The changeimage(src) function receives a parameter src, which is the src attribute value of the clicked thumbnail.
  • document.getElementById("main") is used to get the main image element in HTML with id "main".
  • mainImage.src = src; This line is the key to implementing image switching. It updates the src attribute value of the main image element to the src parameter received by the changeimage function, thereby realizing dynamic switching of the main image content when clicking the thumbnail.

4. Key points and precautions

When building and debugging a picture gallery, you need to pay special attention to the following points, which are the key to ensuring the normal interaction of the gallery:

  • Correctness of image paths : This is the most common reason why galleries “not interact” or display blank/breaking pictures. Be sure to make sure that the image path pointed to by the src attribute of all Building an interactive JavaScript picture gallery: Implementing dynamic picture switching function tags in HTML is correct and accessible.

    • For local images, check if the relative path is correct (e.g. images/dublin culture1.jpg).
    • For network images, make sure the URL is complete and the image server allows cross-domain access (if your page and image are not under the same domain). In the example, we used the URL of the common image bed to ensure that the image can be loaded and demonstrated properly.
  • JavaScript file introduction order : Make sure your JavaScript code is executed after the HTML structure is loaded. Usually, it is a good habit to put the <script> tag before the </script>

The above is the detailed content of Building an interactive JavaScript picture gallery: Implementing dynamic picture switching function. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

PHP Tutorial
1540
276
Essential HTML Tags for Beginners Essential HTML Tags for Beginners Jul 27, 2025 am 03:45 AM

To get started with HTML quickly, you only need to master a few basic tags to build a web skeleton. 1. The page structure is essential, and, which is the root element, contains meta information, and is the content display area. 2. Use the title. The higher the level, the smaller the number. Use tags to segment the text to avoid skipping the level. 3. The link uses tags and matches the href attributes, and the image uses tags and contains src and alt attributes. 4. The list is divided into unordered lists and ordered lists. Each entry is represented and must be nested in the list. 5. Beginners don’t have to force memorize all tags. It is more efficient to write and check them while you are writing. Master the structure, text, links, pictures and lists to create basic web pages.

Shadow DOM Concepts and HTML Integration Shadow DOM Concepts and HTML Integration Jul 24, 2025 am 01:39 AM

ShadowDOM is a technology used in web component technology to create isolated DOM subtrees. 1. It allows the mount of an independent DOM structure on ordinary HTML elements, with its own styles and behaviors, and does not affect the main document; 2. Created through JavaScript, such as using the attachShadow method and setting the mode to open; 3. When used in combination with HTML, it has three major features: clear structure, style isolation and content projection (slot); 4. Notes include complex debugging, style scope control, performance overhead and framework compatibility issues. In short, ShadowDOM provides native encapsulation capabilities for building reusable and non-polluting UI components.

What is the name attribute in an input tag for? What is the name attribute in an input tag for? Jul 27, 2025 am 04:14 AM

Thenameattributeinaninputtagisusedtoidentifytheinputwhentheformissubmitted;itservesasthekeyinthekey-valuepairsenttotheserver,wheretheuser'sinputisthevalue.1.Whenaformissubmitted,thenameattributebecomesthekeyandtheinputvaluebecomesthevalueinthedatasen

How to embed a PDF document in HTML? How to embed a PDF document in HTML? Aug 01, 2025 am 06:52 AM

Using tags is the easiest and recommended method. The syntax is suitable for modern browsers to embed PDF directly; 2. Using tags can provide better control and backup content support, syntax is, and provides download links in tags as backup solutions when they are not supported; 3. It can be embedded through Google DocsViewer, but it is not recommended to use widely due to privacy and performance issues; 4. In order to improve the user experience, appropriate heights should be set, responsive sizes (such as height: 80vh) and PDF download links should be provided so that users can download and view them themselves.

Can you put a  tag inside another  tag? Can you put a tag inside another tag? Jul 27, 2025 am 04:15 AM

❌Youcannotnesttagsinsideanothertagbecauseit’sinvalidHTML;browsersautomaticallyclosethefirstbeforeopeningthenext,resultinginseparateparagraphs.✅Instead,useinlineelementslike,,orforstylingwithinaparagraph,orblockcontainerslikeortogroupmultipleparagraph

HTML `style` Tag: Inline vs. Internal CSS HTML `style` Tag: Inline vs. Internal CSS Jul 26, 2025 am 07:23 AM

The style placement method needs to be selected according to the scene. 1. Inline is suitable for temporary modification of single elements or dynamic JS control, such as the button color changes with operation; 2. Internal CSS is suitable for projects with few pages and simple structure, which is convenient for centralized management of styles, such as basic style settings of login pages; 3. Priority is given to reuse, maintenance and performance, and it is better to split external link CSS files for large projects.

How to create an unordered list in HTML? How to create an unordered list in HTML? Jul 30, 2025 am 04:50 AM

To create an HTML unordered list, you need to use a tag to define a list container. Each list item is wrapped with a tag, and the browser will automatically add bullets; 1. Create a list with a tag; 2. Each list item is defined with a tag; 3. The browser automatically generates default dot symbols; 4. Sublists can be implemented through nesting; 5. Use the list-style-type attribute of CSS to modify the symbol style, such as disc, circle, square, or none; use these tags correctly to generate a standard unordered list.

How to use the contenteditable attribute? How to use the contenteditable attribute? Jul 28, 2025 am 02:24 AM

ThecontenteditableattributemakesanyHTMLelementeditablebyaddingcontenteditable="true",allowinguserstodirectlymodifycontentinthebrowser.2.Itiscommonlyusedinrichtexteditors,note-takingapps,andin-placeeditinginterfaces,supportingelementslikediv

See all articles