Every time you iterate through your loop, you are wiping out the last value for window.onclick
and setting a new function as its value. Use .addEventListener()
to register event handlers.
Now, having said that, you have a problem with i
being used in your callback function because i
is declared at a higher level, so a closure is created around it. You can read more about closures here. The closure is causing the event handling functions to all be looking for modal[3]
because that is the last value i
was set to when the loop exited.
To avoid the closure and to correct the overwriting of window.onclick
, the script should be:
<script>
// Use modern standards to set up event handlers:
window.addEventListener("click", testModal)
function testModal(event){
var modal = ["box-search","login","register"];
// Use the built-in Array.prototype.forEach method to loop
// through the array elements, thus avoiding a numeric counter
modal.forEach(function(element){
// Search the DOM for elements that have id'sthat
// match the modal array's id's
var el = document.getElementById(element);
// Check the found element
if (event.target == el) {
el.style.display = "none";
}
});
}
</script>