Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

window.onclick = function(event) only works for first item

Tags:

javascript

Here is a jsfiddle of my complete code, where you can test the functionality of the two modals. Clicking outside the second modal closes it, while clicking outside the first modal does not close it.

I have two modal pop-up windows on an HTML page, and after they're opened, they can be closed by clicking outside of the modal with this code:

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

For some reason, this code only works for the second (last) instance of it in my script.js file. You can see that there are really just two blocks of code in this file: the first controls the first modal, and the second controls the second modal. Each instance of the code above is at the end of the block.

// Get modalCompanies
var modalCompanies = document.getElementById('companiesModal');

// Get button that opens the modalCompanies
var btnCompanies = document.getElementById("companiesOpen");

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

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

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

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



// Get modalPrivacy
var modalPrivacy = document.getElementById('privacyModal');

// Get button that opens the modalPrivacy
var btnPrivacy = document.getElementById("privacyOpen");

// Get <spanPrivacy> element that closes the modalPrivacy
var spanPrivacy = document.getElementsByClassName("close")[1];

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

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

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

What is preventing the window.onclick = function(event) { } function at the end of each block from being functional in both blocks?

like image 841
rpivovar Avatar asked Nov 27 '22 08:11

rpivovar


1 Answers

use

window.addEventListener("click", function(event) {
});

instead of

window.onclick = function() {
}

https://jsfiddle.net/qsL76mx6/

like image 108
Maxim Kuzmin Avatar answered Dec 09 '22 17:12

Maxim Kuzmin