'How can I make a more efficient DOM function?

I have 6 images on a page that I can click to enlarge using modal container and add or removing an opacity. I will be doing the same on a second page and am trying to work out how to shorten the code rather than individually write out each one.

The HTML looks like:

<section class="container-footwear">
    <div class="article-large">
      <article class="footwear">
        <p>
          <img
            src="images/KSwiss.jpg"
            alt=""
            class="footwear-image"
            id="fi-1"
          />Text
        </p>
      </article>
    </div>
    <div class="modal-container" id="modal-container1">

      <div class="modal">
        <img class="modal-img" src="images/KSwiss.jpg" alt="" />
        <button class="footwear-button" id="close1">x</button>
      </div>
    </div>
    ...(this carries on using the same pattern to id="fi-6")
 </section>

Then the CSS concerning the modal container is:

.modal-container {
display: flex;
align-items: center;
justify-content: center;
position: fixed;
opacity: 0;
pointer-events: none;
top: 0;
left: 0;
height: 100vh;
width: 100%;
background-color: rgba(0, 0, 0, 0.2);
transition: opacity 0.3s ease;
}
.modal-container.show {
  pointer-events: auto;
  opacity: 1;
  z-index: 999;
}

and the JS that controls is like this:

// Article 1. //Initialising the variables that hold the ID of the image.

const open1 = document.getElementById("fi-1");

const modalContainer1 = document.getElementById("modal-container1");

const close1 = document.getElementById("close1");

//Adding the function to change the opacity through the show selector.

open1.addEventListener("click", () => {
  modalContainer1.classList.add("show");
});

close1.addEventListener("click", () => {
  modalContainer1.classList.remove("show");
});

I've tried using a loop or a new function that is called onclick in the HTML. I'm not familiar enough with DOM stuff yet to know all the different commands. Can anyone give me a pointer in the right direction? There must be a way to have one function that reacts to whatever image is clicked rather than repeat the same commands over and over just for a new image id.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source