1

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>

1 Answer 1

3

Problem is that you declare the same variable 3 times with 3 different values. Your variable is declared globally. So it will be overwritten every time.

Also, the solution would be to add a common property to all modals ( eg. a className ) . Select them all. See which one is clicked and do stuff with it.

See below a simplistic example

const modals = document.querySelectorAll('.modal')

const doStuffWithModal = (modal) => modal.style.display = 'none'

modals.forEach(modal => modal.addEventListener('click', () => doStuffWithModal(modal)))
.modal {
width: 100px;
height:100px;
background:red;
margin: 20px
}

.modal.container-two {
  background:blue
}
.modal.container-three {
    background: green
}
<div id="window-one" class="container-one modal"></div>
<div id="window-two" class="container-two modal "></div>
<div id="window-three" class="container-three modal" ></div>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.