0

I'm trying to code a page where, on clicking different areas of a map, different modals with different content pop up. However, when I click on either area, the same content shows up (and the "close" button doesn't work). I gave them different IDs, and they get triggered by different areas. Do you have an idea what the problem can be?

Here's what I have:

.modal { display: none; /* Hidden by default */
position: fixed; /* Stay in place */
z-index: 1; /* Sit on top */
left: 0; top: 0; } /* Modal Content/Box */

.modal-content { margin: 15% auto; padding: 20px; } /* The Close Button */

.close { float: right;
font-size: 28px; }

.close:hover, .close:focus { color: black; text-decoration: none; cursor: pointer; }
<map name="2042434">
        <area onclick="myFunction1()" shape="poly" coords="46,59,65,45,96,70,198,95,337,173,348,217,348,274,391,296,361,438,235,440,238,258,48,59,61,64" alt="">
        <area onclick="myFunction2()" shape="poly" coords="393,296,349,274,347,217,374,208,425,230,440,203,429,162,446,152,513,192,548,184,582,238,577,329,493,380,490,398,409,435,362,440,380,336" alt="">
        </map>
<img src="https://www.google.com/imgres?imgurl=https%3A%2F%2Fguide-goyav.com%2Fwp-content%2Fuploads%2F2020%2F05%2FSecteur-de-la-ville.png&imgrefurl=https%3A%2F%2Fguide-goyav.com%2Fvisiter-grenoble%2F&tbnid=3gtWJdaEDshRYM&vet=12ahUKEwjc1tGmvdX4AhUa04UKHWylBqsQMygeegUIARCJAg..i&docid=Zqq3LZ57uAb2-M&w=618&h=626&q=carte%20grenoble&ved=2ahUKEwjc1tGmvdX4AhUa04UKHWylBqsQMygeegUIARCJAg" alt="" border="0" width="703" height="794" usemap="#2042434">

<!-- MODAL 1 -->
<div id="modal1" class="modal">
    <div class="modal-content">
    <span class="close">&times;</span> <!--the close button-->
    <p>Some text in the Modal..</p>
    </div>
</div>

<script>var modal=document.getElementById("modal1");
var span=document.getElementsByClassName("close")[0];

function myFunction1() {
  modal.style.display="block";
}

span.onclick=function() {
  modal.style.display="none";
}

window.onclick=function(event) {
  if (event.target==modal1) {
    modal.style.display="none";
  }
}

</script>

<!-- MODAL 2 -->

<div id="modal2" class="modal">
    <div class="modal-content">
    <span class="close">&times;
    </span><p>So2ext 2 th2Mo22..</p>
    </div>
</div>

<script>var modal=document.getElementById("modal2");
var span=document.getElementsByClassName("close")[0];

function myFunction2() {
  modal.style.display="block";
}

span.onclick=function() {
  modal.style.display="none";
}

window.onclick=function(event) {
  if (event.target==modal2) {
    modal.style.display="none";
  }
}

</script>

---------solution/final code----------

            <map name="2042434">
            <area id="area1" shape="poly" coords="46,59,65,45" alt="">
            <area id="area2" shape="poly" coords="393,296,349,274" alt="">
            </map>
            <img src="https://www.google.com/imgres?imgurl=https%3A%2F%2Fguide-goyav.com%2Fwp-content%2Fuploads%2F2020%2F05%2FSecteur-de-la-ville.png&imgrefurl=https%3A%2F%2Fguide-goyav.com%2Fvisiter-grenoble%2F&tbnid=3gtWJdaEDshRYM&vet=12ahUKEwjc1tGmvdX4AhUa04UKHWylBqsQMygeegUIARCJAg..i&docid=Zqq3LZ57uAb2-M&w=618&h=626&q=carte%20grenoble&ved=2ahUKEwjc1tGmvdX4AhUa04UKHWylBqsQMygeegUIARCJAg" alt="" border="0" width="703" height="794" usemap="#2042434">
                                        
                                    <!-- MODAL SEC1 -->
<div id="modal1" class="modal">
  <div class="modal-content">
  <span class="close">&times;</span>
  <p>Some text in the Modal..</p>
  </div>
</div>
                                        
                                    <!-- MODAL SEC2-->
<div id="modal2" class="modal">                                                                            
  <div class="modal-content">                                                                            
  <span class="close">&times;</span>                                                                           
  <p>So2ext 2 th2Mo22..</p>                                                                            
  </div>
</div>


<script>
function closeModal() {
                                             
 document.querySelectorAll('.modal').forEach(function (modal) {
  modal.style.display = 'none';
  })
}

                                        document.querySelectorAll('span.close').forEach(function (element) {
//close all modal
                                             
 element.addEventListener('click', function (e) {
 closeModal();
 })
});


(function myFunction1() {

// your code here will be safe and won't pollute other areas of your code
 var modal = document.getElementById("modal1");
 var span = document.getElementsByClassName("close")[0];
 var area = document.getElementById("area1");                                                                    

 area.onclick = function() {
  modal.style.display = "block";
 }
                                             
 span.onclick = function() {
  modal.style.display = "none";
  }
                                             
 window.addEventListener('click', function(event) {
  if (event.target==modal1){
   closeModal();
  }
 });
})();
                                        
(function myFunction2() {

 var modal = document.getElementById("modal2");
 var span = document.getElementsByClassName("close")[0];
 var area = document.getElementById("area2");                                                                    
 
 area.onclick = function() {
   modal.style.display = "block";
 }
                                             
 span.onclick = function() {
  modal.style.display = "none";
 }

 window.addEventListener('click', function(event) {
  if (event.target==modal2){
   closeModal();
  }
 });

})();
</script>
anks
  • 3
  • 2
  • 2
    _"Do you have an idea what the problem can be?"_ - that fact that you are overwriting the global variables `modal` and `span`, as well as `window.onclick`. – CBroe Jun 30 '22 at 13:21
  • If you place each script inside IIFE it would work without too much customizations – IT goldman Jun 30 '22 at 13:29
  • By declaring your variable directly inside a ` – miken32 Jun 30 '22 at 15:34
  • Does this answer your question? [What is the scope of variables in JavaScript?](https://stackoverflow.com/questions/500431/what-is-the-scope-of-variables-in-javascript) – miken32 Jun 30 '22 at 15:34

2 Answers2

0

<button id="btn1">button 1</button>
<button id="btn1">button 2</button>

<script>
  (function() {

    // your code here will be safe and won't pollute other areas of your code
    // however, window.something is global and shared by your code
    
  })();
</script>
IT goldman
  • 14,885
  • 2
  • 14
  • 28
  • Ok! Do I need one of those for each modal? And do I just add the variables in it, or the function too? – anks Jun 30 '22 at 15:58
  • update: one for each modal and it works! (each area opens different modal content) But the modals don't close anymore, either by clicking away or with the close button. I tried putting the span.onclick and window.onclick sections inside and outside the IIFE. Should I also modify them somehow? – anks Jun 30 '22 at 16:28
  • You *can* attach several events to window, but not if you use same property `window.onclick` you will overwrite it. The proper way is to do `window.addEventListenet('click', function(event) {})`. – IT goldman Jun 30 '22 at 17:10
  • 1
    Also using some lines from Ngannv's code, I managed to make it work! Thank you v much for the help! – anks Jun 30 '22 at 17:48
-2
<div id="modal1" class="modal">
            <div class="modal-content">
                <span class="close">&times;</span> <!--the close button-->
                <p>Some text in the Modal..</p>
            </div>
        </div>

        <!-- MODAL 2 -->
        <div id="modal2" class="modal">
            <div class="modal-content">
                <span class="close">&times;</span>
                <p>So2ext 2 th2Mo22..</p>
            </div>
        </div>
        
        function closeModal() {
            document.querySelectorAll('.modal').forEach(function (modal) {
                modal.style.display = 'none';
            })
        }

        document.querySelectorAll('span.close').forEach(function (element) {
            //close all modal
            element.addEventListener('click', function (e) {
                    closeModal();
                }
            )
        });
        document.querySelectorAll('.modal').forEach(function (element) {
            //close all modal
            element.addEventListener('click', function (e) {
                    e.stopPropagation();
                    e.preventDefault();
                }
            )
        });

        function myFunction1() {
            let modal = document.getElementById("modal1");
            modal.style.display = "block";
        }

        function myFunction2() {
            let modal = document.getElementById("modal2");
            modal.style.display = "block";
        }
        const getParents = el => {
            for (var parents = []; el; el = el.parentNode) {
                parents.push(el.id);
            }

            return parents.join(',');
        };
        document.body.addEventListener('click', (e) => {
            let element = getParents(e.target);//return: ,,modal2,,, or ,,modal1,,,
            if(element.includes("modal")===-1){
                //click outside modal
                closeModal();
            }
        }, true);
CodeZi.pro
  • 229
  • 5
  • 8