JavaScript MODAL windows should be closing by clicking anywhere, but it's not

I’ve created a CSS grid which has five buttons. Each to open different modal window. These windows should be able to close by pressing the top right X or anywhere outside the window.

  1. Why the JavaScript only works in the final window (#poravasara)?
  2. My JavaScript coda has lots of repetition. Is there a way to pack it, or write it more efficient?

You can find the DEMO in CodePen

Hi @konstantinnikkari, this is because you’re reassigning the window.onlick property for each modal, so only the last one will remain – to add multiple event listeners, use addEventListener() instead (which you should do anyway for good practice, see here for some more explanations).

Yes certainly. :-) First, you might store the modal ID for each button as a data attribute; so your markup would be something like

<button id="avaaVasara" class="valitsija" data-show-modal="vasaraIkkuna">+</button>
<button id="avaaPoravasara" class="valitsija" data-show-modal="poravasaraIkkuna">+</button>

Then in your JS, you loop over those buttons and add event listeners to show / hide the corresponing modal:

var selectors = document.querySelectorAll('.valitsija')

selectors.forEach(function (selector) {
  var modal = document.getElementById(selector.dataset.showModal)
  var close = modal.querySelector('.close')

  selector.addEventListener('click', function () { = 'block'

  window.addEventListener('click', function (event) {
    if ( === modal || === close) { = 'none'

Here’s an updated pen.


Thank you Mentor m3g4p0p. :blush:

1 Like