0

I have a basic problem with showing modal. Everything is working ok, but only for second click. I am sure, I have some mistake in js code. Can you help me please?

HTML code:

    <div class="flex flex-col lg:flex-row justify-center px-3 lg:px-0">
     <div class="pb-3 lg:pb-0 lg:p-5 cursor-pointer">
      <img onclick="showImage('planek1')" id="planek1" src="assets/imgs/planek1.jpg" alt="">
     </div>
     <div class="cursor-pointer lg:p-5">
      <img onclick="showImage('planek2')" id="planek2" src="assets/imgs/planek2.jpg" alt="">
     </div>
    </div>
    <div id="myModal" class="modal">
     <span class="close">&times;</span>
     <img class="modal-content" id="img01">
     <div id="caption"></div>
    </div>

Javascript code:

    function showImage(id) {
     const modal = document.getElementById("myModal");
     const img = document.getElementById(id);
     const modalImg = document.getElementById("img01");
     img.onclick = function () {
      modal.style.display = "block";
      modalImg.src = this.src;
    };
    const span = document.getElementsByClassName("close")[0];
    span.onclick = function () {
     modal.style.display = "none";
    };
   }
3
  • 3
    Your event listener registers another event listener, why is that? Commented Nov 2, 2020 at 17:51
  • I guess there is a problem - i wanted to use only one function for two different pics, because they are doing same thing Commented Nov 2, 2020 at 17:57
  • Good idea, the problem is you don't want to execute that function on the click event, please take a look at my answer Commented Nov 2, 2020 at 18:09

1 Answer 1

2

Try removing onclick="showImage('planek2')", give a class="triggers-modal" to your elements, and write this JavaScript:

const modalImg = document.getElementById("img01");
const span = document.getElementsByClassName("close")[0];
span.onclick = function () {
    modal.style.display = "none";
};

Array.from(document.getElementsByClassName('triggers-modal')).forEach(element => {
        element.onclick = function () {
            modal.style.display = "block";
            modalImg.src = this.src;
        };
    });

This code defines the modal behavior for every element that has the triggers-modal class name instead of the onclick event which is inappropriate.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.