Leveraging JavaScript code repeatedly

Apologies if this question has been asked before, as I couldn't find it.

I have an HTML table with images used as buttons:

<td>
  <button class="trigger">
    <img src="D:\Elly Research\ CO2858\Presentation\Calypso_map.jpg">
  </button>
</td>

<div class="modal">
  <div class="modal-content">
    <span class="close-button">&times; </span>
    <img src="D:\Elly Research\CO2858\Presentation\Calypso_map.jpg">
    <script src="D:\Elly Research\CO2858\Presentation\modal.js"></script>
  </div>
</div>

A script controls this functionality:

var modal = document.querySelector(".modal");
var trigger = document.querySelector (".trigger");
var closeButton = document.querySelector(".close-button");

function toggleModal() {
  modal.classList.toggle("show-modal");
}

function windowOnClick(event) {
  if(event.target === modal){
    toggleModal();
  }
}

trigger.addEventListener("click", toggleModal);
closeButton.addEventListener("click", toggleModal);
window.addEventListener("click", windowOnClick);

However, when I try to replicate the format for a second image on the same page and table, the script stops working.

Is JavaScript not able to handle multiple elements in the same way that CSS can with IDs?

This is my first time using JavaScript alongside HTML and CSS.

Answer №1

When you run the document.querySelector(".modal") function, it selects the first element with the class "modal". In this case, it would be the div containing the initial picture. After that, you attach a 'click' event to only the first picture.

An alternative approach is to use querySelectorAll, which provides a list of all matched elements. You can then iterate through these nodes to add the 'click' event listener as shown below:

const modals = document.querySelectorAll(".modal");

modals.forEach(modal => {
    modal.addEventListener('click', toggleModal)
});

Answer №2

I'm not entirely sure about the specific question you're asking. However, based on my assumptions, here's a brief code snippet that may assist you.

var modal = document.getElementById("modal")
window.addEventListener("click", windowOnClick);
document.querySelector(".close-button").addEventListener("click", toggleModal)

function showImage(event){
 toggleModal()
  modal.getElementsByTagName("img")[0].src =event.srcElement.src
}

function windowOnClick(event){
  if(event.srcElement === modal){
    toggleModal()
  }
}

function toggleModal(){
  modal.classList.toggle("show-modal")
}
td > img{
  width: 100px;
  height: auto;
}

.modal{
  display: none;
  position: fixed;
  top: 0px;
  left: 0px;
  width: 100%;
  height: 100%;
  background: rgba(0,0,0,0.8);
  z-index=10;
}

.show-modal{
  display: block !important;
}

.modal-content{
  width: 60%;
  height: auto;
  margin: 0 auto;
}

.close-button{
  color: white;
  cursor: pointer;
}

#viewer{
  width:100%;
  height: auto;
}
<!doctype>
<html>
  <head>
  </head>
  <body>
    <table>
      <tr>
        <td>
          <img src="https://i.imgur.com/GV6086A.jpg" onclick="showImage(event)" />
        </td>
        <td>
          <img src="https://i.imgur.com/opERcp1.jpg" onclick="showImage(event)" />
        </td>
      </tr>
      <tr>
        <td>
          <img src="https://i.imgur.com/lieUEvQ.jpg" onclick="showImage(event)" />
        </td>
        <td>
          <img src="https://i.imgur.com/B63gaEQ.jpg" onclick="showImage(event)" />
        </td>
      </tr>
      
    </table>
    <div class="modal" id="modal">
      <div class="modal-content">
       <span class="close-button">&times; </span>
        <img id="viewer">
      </div>
    </div>
  </body>
</html>

Answer №3

In the case of a small application, one possible solution could involve creating an object of images that includes their respective details. This can be achieved by defining the images in the following way:

//By adding properties to the objects, you can customize them as needed
    images = [{
        src: "D:\Elly Research\CO2858\Presentation\Calypso_map.jpg"
    },
    {
        src: "D:\Elly Research\CO2858\Presentation\Calypso_map_alternative.jpg"
    }]

Subsequently, you have the option to iterate over this object to populate your table or directly create the table with specific ID references such as

<button id="0" class="trigger">
. By utilizing the event object array index, you can access these references using the following code:

var id = event.target.id

To dynamically generate the image element within the modal view, the function should resemble the following structure:

function toggleModal(event){
        var id = event.target.id;
        var div = document.getElementsByClassName('modal-content')[0];
        div.innerHTML += '<img class="modal-image" src="'+images[id].src+'" />'; 
        modal.classList.toggle("show-modal");
    }

It is important to remember to remove any existing image elements before adding a new one:

var child = div.querySelector("img");
if(child != null){
    div.removeChild(child);
}

We hope this guidance proves beneficial for your project! Best of luck with your studies!

Answer №4

Utilizing JavaScript multiple times is possible. Be sure to inspect the source of your images. This topic has been previously addressed in this discussion - src absolute path problem.

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's the best way to transform createHmac function from Node.js to C#?

Here's a snippet of code in Node.js: const crypto = require('crypto') const token = crypto.createHmac('sha1', 'value'+'secretValue').update('value').digest('hex'); I am trying to convert t ...

Adjust the HTML layout based on the JSON data provided

I am working with a JSON script that contains live matches, which change every 5 minutes. The changes could involve keys such as live_in or score. Matches are also being deleted and added to the JSON. I want to ensure that my HTML output remains updated at ...

Testing a cucumber scenario by comparing the redirect URL with a different URL

Currently, I am working on writing Cucumber tests for my project. One issue I have encountered is that when clicking a certain button in my code, it redirects to another page with a fixed URL. How can I retrieve the current URL within the Cucumber test? I ...

Using ReactJS to activate child components from a parent component

I am working on a parent component that functions as a Form in my project. export default class Parent extends Component{ submitInput(event){ ...calling Children components } render(){ ...

What is the best way to restrict a React input field to have values within the minimum and maximum limits set by its

As a newcomer to React, I am working on restricting my input to values between -10 and 10. Currently, the input is set up to accept any value, and I am utilizing hooks like useState and useEffect to dynamically change and set the input value. My goal is ...

"Why isn't the reordering functionality functioning properly after the button has been clicked

I have a question regarding menu options that contain text and a button. I need to open the menu option when the button is clicked. Unfortunately, I am facing an issue where rerendering is not working when I click on the button. Here is the link for refer ...

Conceal the cursor within a NodeJS blessed application

I am struggling to hide the cursor in my app. I have attempted various methods like: cursor: { color: "black", blink: false, artificial: true, }, I even tried using the following code inside the screen object, but it didn't work: v ...

Tips for adding a solid background color to a div element

I am struggling with trying to make a full width background-color for a div in my ruby on rails app. Despite setting the background color and margin to 0, I still end up with unwanted margins on the left, right, and top. Below is the code snippet: <!D ...

Solving the CSS Trick: Responsive Data Table (featuring inline editing) Display Glitch

In my quest to create a responsive table with inline editing, I turned to Chris's guide at CSS-Tricks (check it out here). To see how it all comes together, take a look at this Plunker demo. On mobile screens, the responsiveness is on point. https: ...

The difference in percentage padding rendering is specific to Firefox only

In my current project, I have created various responsive boxes for displaying news articles on the website. Everything seems to be functioning well except for the news items within the slider at the top of the main content. Surprisingly, they are displayin ...

Is there a way to refresh a webpage without the need to reload it

Imagine a scenario where a tab on a website triggers the loading of a specific part of the webpage placed within a div. For example, clicking on a tab may trigger the loading of a file named "hive/index.php". Now, if a user selects an option from an auto ...

Retention of user-entered data when navigating away from a page in Angular

I need to find a way to keep the data entered in a form so that it remains visible in the fields even if the user navigates away from the page and then comes back. I attempted to use a solution from Stack Overflow, but unfortunately, it did not work as exp ...

How can the HTML email width be adjusted on Outlook 2016?

When I send out HTML emails, I encounter an issue where the content takes up the full width no matter what. I have tried adjusting the width of table, tr, td, div, and body elements, but it still persists. This problem occurs on Outlook 2016 across all W ...

Is the utilization of the React context API in NextJS 13 responsible for triggering a complete app re-render on the client side

When working with NextJS 13, I've learned that providers like those utilized in the React context API can only be displayed in client components. It's also been made clear to me that components within a client component are considered part of the ...

"Launching a node server in Azure to get you up and running

Currently, I have a Single Page Application that is hosted on Microsoft Azure. This application requires refreshing some dashboard data every 5 seconds. To achieve this, I have developed a nodejs service that continuously requests data from the API and gen ...

What is the most effective way to determine which radio button is currently selected in a group with the same name using JQuery?

<form class="responses"> <input type="radio" name="option" value="0">False</input> <input type="radio" name="option" value="1">True</input> </form> Just tested: $('[name="option"]').is(':checked ...

The Final Div Fluttering in the Midst of a jQuery Hover Effect

Check out my code snippet here: http://jsfiddle.net/ZspZT/ The issue I'm facing is that the fourth div block in my example is flickering quite noticeably, especially when hovering over it. The problem also occurs occasionally with the other divs. Ap ...

Transform a list of file directories into a JSON format using ReactJS

I am developing a function that can convert a list of paths into an object structure as illustrated below; this script will generate the desired output. Expected Output data = [ { "type": "folder", "name": "dir1& ...

The timing of the RequestAnimationFrame function varies based on the dimensions of my canvas

In my application, I have a canvas that dynamically adjusts its CSS size based on the window size. The main gameplay loop in my code looks like this: run = function(){ console.log(timerDiff(frameTime)); game.inputManage(); game.logics(); ...

Using a JQuery variable to display a div using the .show() method

I am attempting to use the .show() method to reveal div elements in a slideshow-like manner. My goal is to utilize the ID of a button on my navigation bar to trigger the display of a specific slide similar to how a slideshow operates. For example, if butt ...