简体   繁体   中英

Unable to close modal in Javascript

I'm writing some js code in my ebook project. The problem is in a modal, used to show, like a popup, reference from others pages. Here is the part of my project dedicated to close the modal.

    // Riferimento al Modal
var modal = document.getElementById('modalversetti');
// Riferimento allo <span> che chiude il Modal
var span = document.getElementsByClassName("close")[0];
// Quando l'utente preme sullo <span> (x), si chiude il Modal
span.onclick = function() {
modal.style.display = "none";
}

And here (better) all the code (js+html+css) showing the modal running but unable to close. https://jsfiddle.net/emanuele_tinari/gkL5sh3x/ Modal built via js run very well, but, unfortunately, close button seems don't. thanks.

Your code tries to find the close span to attach the listener immediately when the page loads. You haven't created the modal at this point, so it fails.

If you cut the chunk of code in your question and paste it immediately at the end of the function that creates your modal, the close button will work.

This will do the work :

  document.onclick = function(event) {
    var el = event.target;
    if (el.className == "close") {
    // Riferimento al Modal
    var modal = document.getElementById('modalversetti');

        modal.style.display = "none";
    }
};

but you have more problems with your code ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM