Tips for updating the modal content with a dynamic approach upon clicking an image

On my HTML page, I have 3 thumbnail images. What I want to achieve is that when a user clicks on any of these images, the clicked image should be displayed in a modal window.

Is there a way to dynamically pass the image name into the modal-body every time an image is clicked?

<a href="images/Picture1.jpg" data-bs-toggle="modal" data-bs-target="#exampleModal">
  <img src="images/Picture1.jpg" alt="image not available" onclick=check(this)>
</a>
<a href="images/Picture2.jpg" data-bs-toggle="modal" data-bs-target="#exampleModal">
  <img src="images/Picture2.jpg" alt="image not available" onclick=check(this)>
</a>
<a href="images/Picture3.jpg" data-bs-toggle="modal" data-bs-target="#exampleModal">
  <img src="images/Picture3.jpg" alt="image not available" onclick=check(this)>
</a>

Modal

<div class="modal fade" id="exampleModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
  <div class="modal-dialog modal-lg">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="exampleModalLabel">Image</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <div class="modal-body">
        <img src="images/Picture1.jpg" alt="image not available" id="imagepreview" style="width: 100%; height: 100%;">
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
      </div>
    </div>
  </div>
</div>

Javascript function to track the clicked image

function check(img) {
  var src = img.src.replace(/^.*[\\\/]/, "");
  console.log(src);
}

Answer №1

If you want to switch the image in your modal-body with the one that was clicked, simply replace the src attribute of the image.

Each image triggers a function called check when clicked, passing the clicked img element as a parameter.

To update the image in your modal based on its id, use document.getElementById() and set the modal image's src equal to the clicked img element's src.

function check(img) {
  document.getElementById("imagepreview").src = img.src;
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What are some ways to prevent a submit event from occurring?

When my form is submitting, I am executing a function. $('#form-target').submit(function(){ makechange(); return false; }); However, there are situations where I need to prevent this event from happening. ...

Fade out the jQuery message after a brief 2-second pause

In my Rails application, I encountered an issue with a flash message that appears after successfully completing an AJAX action. The message displays "Patient Added" but does not include a way to close it without refreshing the page. To address this, I atte ...

What is the best way to incorporate the 'autoskip' functionality into chartjs?

Click here for an example I've been attempting to utilize the autoSkip functionality outlined in the documentation for chart.js: Visit this link for more information on autoSkip The current issue I'm facing is that my x-axis labels are o ...

Having trouble establishing a default route with React Router v5

I am facing an issue with setting the default route to the home page in react router v5. Despite trying several methods, I cannot get it to work as expected. Index.js import React from "react"; import ReactDOM from "react-dom"; import ...

Creating a hierarchical structure for three interconnected lists within SharePoint Online by utilizing JavaScript

We currently have a network of interconnected SharePoint lists: Department list Category List - which includes a lookup field linked to the Department list. Asset list - with a lookup field connected to the Category list. Is there a method, utilizi ...

Issue with page layout arises due to a problem with AngularJS directive

I recently downloaded the Ace Admin template from As I tried to integrate it into my AngularJS project, I encountered a problem when using specific parts of the template in custom directives. To isolate and simplify the issue, I created a plunker at https ...

I'm attempting to save my information with react-redux, but unfortunately, it's not working as expected. Any ideas on how to troubleshoot

Working on a React project, storing data using Postman works well, but with React-Redux, the data doesn't pass into the database. How can this be resolved? Below are snippets of the code: const mongoose = require('mongoose'); const verifySc ...

The special function fails to execute within an "if" condition

As a newcomer to JavaScript/jQuery and Stack Overflow, I kindly ask for your patience in case there are any major errors in my approach. I am currently developing an HTML page with Bootstrap 3.3.7, featuring a pagination button group that toggles the visib ...

Locate a particular word in every element within an array range (angularjs)

I'm just getting started with learning angularjs and I would appreciate some kindness as a beginner. Currently, I am working on creating a poll app using angular. In my project, I have an array scope named items, which holds all the items to be adde ...

Setting the font size for the entire body of a webpage globally is ineffective

Technology Stack: Nuxt.js + Vuetify.js Problem: Unable to set global body font size Solution Attempt: I tried to adjust the body font size to 40px in ~/assets/style/app.styl: // Import Vuetify styling ...

What is preventing Protractor from detecting Angular on a site that has been automatically initialized with Angular?

Whenever I try to utilize browser.get() in my code, I encounter the following error: Error: Angular could not be found on the page http://localhost:5000/#/login debug=timing&saveLogs=true&displayAll=true : angular never provided resumeBootstrap A ...

What is the best way to filter out duplicate objects in JavaScript?

I have the following code snippet: let self = this; self.rows = []; self.data.payload.forEach(function (item, index) { if (!(self.rows.includes(item))) { self.rows.push(item); } }); The issue is that includes always returns false. Each ite ...

Vertical words standing alongside an upright line

My goal is to rotate the text without any issues, but I'm having trouble with the line underneath it. The line should adjust its length based on the length of the text. In other words, as the text changes in length, the line should shrink or expand ac ...

What steps can be taken in Next.js to display a 404 page when data is not retrieved from the Wordpress admin?

I am working with JSON data that looks like this: [ { "taxonomy_slug": "product_cat", "taxonomy_name": "Categories", "frontend_slug": "product-category" }, { ...

Using lambda expressions to sort through an array of objects in React

My goal is to create a delete button that removes items from a list and updates the state variable accordingly. public OnDeleteClick = (): void => { const selectionCount = this._selection.getSelectedCount(); let newArray = this.state.items; for ...

What is the best way to upload a file without finalizing the form submission?

I have been working on a task to upload a file using ajax and php without refreshing the page when submitting. My code seems to be functioning well and alerts a valid message when I use the preg_match function. However, when I include the rest of the valid ...

Drag and Drop elements between two papers using Joint.js

I am facing a challenge with synchronizing the offset of a dragged element with the cursor position while implementing drag and drop between two papers on my HTML page. My limited experience with CSS might be causing issues with element positioning. Here ...

employing this for the second parameter

Utilizing this.value for $(".selector") is my goal with $("#style_background") serving as my save button. However, when I implement this code, the value coming through is 'save'. How can I achieve this using dania and seablue? $("#style_backgrou ...

Modifying Table Cell Backgrounds Based on Value in React Tables

I am currently utilizing reactstrap to design my table and employing axios to interact with my backend data. The objective is to dynamically change the background color of a cell based on its value. For instance, if the cell value is less than 0.25, it sh ...

"Exploring the possibilities of combining AngularJS with PHP to manipulate

Recently, I started diving into AngularJS and encountered a situation where I needed to fetch data from a database as an array using a foreach function. Here is a snippet of the code I used: <ul> <?php foreach($Items as $Item):?> ...