Having issues closing modal forms with Javascript

I am having some issues with closing my modal pop-up forms, one of them closes, though the other one does not. I am not really sure where the problem lies, it must be something trivial though. I have just started learning JS seriously, so I'd appreciate some help with it. I must add that both of the modals open just fine.

    // Get the modal
    var modal = document.getElementById('modal');

    // Get the button that opens the modal
    var btn = document.getElementById("regbtn");

    // Get the modal
    var signinmodal = document.getElementById('signinmodal');

    // Get the button that opens the modal
    var signinbtn = document.getElementById("signinbtn");

    // Get the <span> element that closes the modal
    var span = document.getElementsByClassName("close")[0];

    // When the user clicks on the button, open the modal
    btn.onclick = function() {
        modal.style.display = "block";
    }

    // When the user clicks on the button, open the modal
    signinbtn.onclick = function() {
        signinmodal.style.display = "block";
    }

    // When the user clicks on <span> (x), close the modal
    span.onclick = function() {
        modal.style.display = "none";
    }

    // When the user clicks anywhere outside of the modal, close it
    window.onclick = function(event) {
        if (event.target === modal) {
            modal.style.display = "none";
        }
    }

    // When the user clicks on <span> (x), close the modal
    span.onclick = function() {
        signinmodal.style.display = "none";
    }

    // When the user clicks anywhere outside of the modal, close it
    window.onclick = function(event) {
        if (event.target === signinmodal) {
            signinmodal.style.display = "none";
        }
    }

1 answer

  • answered 2018-10-11 19:23 Johan

    When you assign window.onclick = ... twice you override the last assignment to it, just like if you would assign a value to a variable:

    val = 5;
    val = 7; // 5 is now gone
    

    You should combine them to the same function call to ensure that the events will persist

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

    The same applies for the span tag

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