Is there a way to create a universal script that works for all modal windows?

I have a dozen images on the page, each opening a modal when clicked. Currently, I've created a separate script for each modal. How can I consolidate these scripts into one for all modals?

<!-- 1 Modal-->
<div class="gallery_product col-lg-3 col-md-3 col-sm-3 col-xs-3 filter mercoledì ombra">
<img onclick="myLele(this)" src="https://www.festadellamusicact.it/wp-content/uploads/leletronika.jpg" id="myImg" class="img-responsive"></div>
<div id="lele" class="modal">
<div class="modal-content" id="img11">
<span onclick="undici.style.display = 'none'" class="close">&times;</span>
<img src="https://www.festadellamusicact.it/wp-content/uploads/33407528_10216104175664929_3838668853781463040_n.jpg" class="img-responsive img-modale"></div>
</div> 
<!-- 2 Modal-->
<div class="gallery_product col-lg-3 col-md-3 col-sm-3 col-xs-3 filter mercoledì ombra">
<img onclick="myJessy(this)" src="https://www.festadellamusicact.it/wp-content/uploads/jessy.jpg" id="myImg" class="img-responsive"></div>
<div id="jessy" class="modal">
<div class="modal-content" id="img10">
<span onclick="dieci.style.display = 'none'" class="close">&times;</span>
<img src="https://www.festadellamusicact.it/wp-content/uploads/29543_497687346938913_28179288_n.jpg" class="img-responsive img-modale"></div>
</div>

<script>
   var undici = document.getElementById('lele');
   var lele = document.getElementById("img11");

    function myLele(el) {
        var ImgSrc = el.src;
        undici.style.display = "block";
        lele.src = ImgSrc;
    }

    window.onclick = function (event) {
        if (event.target == undici) {
            undici.style.display = "none";
        }
    }
    
    var dieci = document.getElementById('jessy');
    var jessy = document.getElementById("img10");

    function myJessy(el) {
        var ImgSrc = el.src;
        dieci.style.display = "block";
        jessy.src = ImgSrc;
    }

    window.onclick = function (event) {
        if (event.target == dieci) {
            dieci.style.display = "none";
        }
    }
</script>

I have explored different approaches but haven't been successful in making multiple modals work on the same page. Is it possible to use a foreach () loop for this purpose?

Answer №1

Every element should have a unique ID assigned to it. Make sure to change the IDs of your images from myImg to something distinct like myImg1 and myImg2 for each.

You can simplify the process of toggling modals by utilizing Bootstrap's built-in modal feature. Simply include

data-toggle="modal" data-target="#lele"
for the first modal image, and
data-toggle="modal" data-target="#jessy"
for the second modal image as shown below:

<img src="/leletronika.jpg" id="myImg1" class="img-responsive" data-toggle="modal" data-target="#lele">
<img src="/jessy.jpg" id="myImg2" class="img-responsive" data-toggle="modal" data-target="#jessy">

Don't forget to add the data-dismiss attribute to your close button like this:

<span class="close" data-dismiss="modal">&times;</span>

To see a practical demonstration of the changes mentioned above, you can refer to the following Code Snippet:

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.0/umd/popper.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/js/bootstrap.min.js"></script>
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css" rel="stylesheet"/>

<!-- 1 Modal-->
<div class="gallery_product col-lg-3 col-md-3 col-sm-3 col-xs-3 filter mercoledì ombra">
  <img src="https://www.festadellamusicact.it/wp-content/uploads/leletronika.jpg" id="myImg1" class="img-responsive" data-toggle="modal" data-target="#lele">
</div>
<div id="lele" class="modal">
  <div class="modal-content" id="img11">
    <span class="close" data-dismiss="modal">&times;</span>
    <img src="https://www.festadellamusicact.it/wp-content/uploads/33407528_10216104175664929_3838668853781463040_n.jpg" class="img-responsive img-modale">
  </div>
</div> 
<!-- 2 Modal-->
<div class="gallery_product col-lg-3 col-md-3 col-sm-3 col-xs-3 filter mercoledì ombra">
  <img src="https://www.festadellamusicact.it/wp-content/uploads/jessy.jpg" id="myImg2" class="img-responsive" data-toggle="modal" data-target="#jessy">
</div>
<div id="jessy" class="modal">
  <div class="modal-content" id="img10">
    <span class="close" data-dismiss="modal">&times;</span>
    <img src="https://www.festadellamusicact.it/wp-content/uploads/29543_497687346938913_28179288_n.jpg" class="img-responsive img-modale">
  </div>

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

Having trouble with the date format in the highCharts range selector?

I am encountering an issue while trying to implement the rangefilter feature with HighCharts. The start and end dates are appearing incorrect, indicating that my date is not being recognized properly. My x-axis consists of unique dates as categorical valu ...

Troubleshoot: Why is my Bootstrap 3 responsive navigation bar not functioning

When using drop down items that are longer in length, they tend to wrap down to the next level rather than overflowing. I am not well-versed in @media queries, but I've noticed that on mobile devices the dropdown collapses in the navigation menu, whil ...

Verify the validation of the text box

Checking a textbox control for validation is necessary. Validation Criteria: Value should be between 0 and 1000, with up to 2 decimal places (e.g. 1.00, 85.23, 1000.00). Once 2 decimal points are used, users should not be able to enter additional ze ...

Arranging the 1st element of the 1st row to be placed at the end using CSS Flex

One of my challenges involves choosing between two options: https://i.sstatic.net/JpWiGfW2.png In my project, I am utilizing a container with flex-wrap: wrap to showcase items of equal dimensions. However, the first item in this container stands out due t ...

Choosing the state object name dynamically within a React JS component

I have a quick question about updating state in React. How can I change a specific object in a copy of the state that is selected using e.target.name and then set to e.target.value? For example, if I want to change newState.age when e.target.name = age i ...

Discover how to use your own search engine suggestions within the search bar of Google Chrome

I recently created a search engine on my website, and everything seems to be working perfectly when I visit the search page. However, I wanted to streamline the process by searching directly from the search box in Chrome. After adjusting the settings to ...

How do I avoid using an if statement in jQuery to eliminate errors caused by "undefined" values?

Whenever I incorporate third-party plugins, my usual practice is to initiate them in the main application.js file. For example: $('.scroll').jScrollPane(); However, a challenge arises when a page loads without the presence of the scroll class, ...

User disappears from Firebase after refreshing the page

I've encountered an issue with my Firebase login process. After a page refresh, the user authentication is lost. Even though the user data is stored in LocalStorage, it gets deleted upon refresh. const loginform = document.querySelector('.loginfo ...

Modifying the value of an animated status bar using the same class but different section

I need the status bars to work individually for each one. It would be great if the buttons also worked accordingly. I have been trying to access the value of "data-bar" without success (the script is able to process the "data-max"). However, the script see ...

What is the best way to empty an input field after adding an item to an array?

In my Angular 2 example, I have created a simple functionality where users can add items to an array. When the user types something and clicks the button, the input is added to the array and displayed in a list. I am currently encountering two issues: 1 ...

I am encountering difficulties adding an array to Firebase due to the lack of asynchronous nature in Node.js

As a beginner in the world of nodejs, angularjs and firebase, I am encountering issues related to the asynchronous nature of nodejs while trying to load data into firebase. My goal is to search an existing list in firebase, add a new element to it, and wri ...

Achieving an IE7 opacity background while keeping the text unaffected

This is the given HTML code structure (view in JS Fiddle) How can I adjust the background color to be 20% opaque white while keeping the text black? It needs to be compatible with IE7. <ul class="menu"> <li class="first expanded active-trail ...

Having trouble with the sx selector not functioning properly with the Material UI DateTimePicker component

I'm currently working with a DateTimePicker component and I want to customize the color of all the days in the calendar to match the theme color: <DateTimePicker sx={{ "input": { color: "primary.main&quo ...

Why Isn't the Element Replicating?

I've been working on a simple comment script that allows users to input their name and message, click submit, and have their comment displayed on the page like YouTube. My plan was to use a prebuilt HTML div and clone it for each new comment, adjustin ...

What is the best way to retrieve all collections and their respective documents in Firestore using cloud functions?

Seeking to retrieve an array structured as [1year, 1month, etc] with each containing arrays of documents. Currently encountering a challenge where the returned array is empty despite correct snapshot sizes. Unsure if issue lies with push() method implemen ...

Web browser local storage

Looking to store the value of an input text box in local storage when a button is submitted <html> <body action="Servlet.do" > <input type="text" name="a"/> <button type="submit"></button> </body> </html> Any sug ...

Exploring the art of div transitions and animations using React and Tailwind CSS

I successfully implemented the sidebar to appear upon clicking the hamburger icon with a transition. However, I am now facing the challenge of triggering the transition when the close button is clicked instead. I have attempted using conditional operations ...

Issue with converting form data to JSON format

Having an issue converting a filled form in HTML to a JSON request for sending to the server via HTTP POST. Despite having a filled form, the JSON request only shows an empty array. Here is the JavaScript snippet: $("#submitSurveyBtn").on("click", functi ...

Blocked the loading of scripts due to non-compliance with the Content Security Policy directive

Encountering an error with externally loaded scripts: Refusing to load the script 'https://code.jquery.com/jquery-3.4.1.slim.min.js' due to violating the Content Security Policy directive: "script-src 'self' https://ajax.googlea ...

Choosing the Right Project for Developing HTML/Javascript Applications in Eclipse

Whenever I attempt to build a webpage using eclipse, I am presented with two choices: -- A Javascript project -- A Static web project If I opt for the former, setting up run to open a web browser can be quite challenging. If I decide on the latter ...