I am trying to work out how to make a single JavaScript function control multiple divs.
I have multiple divs with different ids and I wrote identical JavaScript functions for each of them separately. However, the functions either don't work or only one of them does.
I think that most likely they are stopping each other from working and I am wondering if there is a way to use a single JavaScript function but keeping the unique ids on the divs.
Here is a very simple example of what I'm working with:
Note: the script is supposed to close a window if a user clicks anywhere outside a "container" window. At the moment, only clicking on the last yellow container
var modal = document.getElementById('window-one');
window.onclick = function(event) {
if (event.target == modal) {
modal.style.display = "none";
}
}
var modal = document.getElementById('window-two');
window.onclick = function(event) {
if (event.target == modal) {
modal.style.display = "none";
}
}
var modal = document.getElementById('window-three');
window.onclick = function(event) {
if (event.target == modal) {
modal.style.display = "none";
}
}
div {
border: solid 2px black;
height: 20px;
background: yellow;
margin: 5px;
}
<div id="window-one" class="container-one">1</div>
<div id="window-two" class="container-two">2</div>
<div id="window-three" class="container-three">3</div>