1

I have some code for the function that runs when a button is clicked in my site:

function shadow() {
    document.getElementById("overlay").style.visibility="visible";
    document.getElementById("dim").style.visibility="visible";
    document.getElementById("dim").onclick="document.getElementById('dim','overlay').style.visibility='hidden'";
}

With overlay being the overlay div that I want to be re-hide-able, and dim being the lower z-index dimmer over the entire page when the function runs. The third line is my attempt at making it so that when an area outside of the overlay is clicked, the dim and overlay go away - help on that would be great!

1 Answer 1

0

The onclick property expects a function reference, not a string. In addition, the getElementById method only accepts a single id parameter, which means that only the first element id that you passed to it would be selected.

Based on the code you provided, it looks like you want something like this (live example):

function shadow() {
  var overlay = document.getElementById('overlay');
  var dim = document.getElementById('dim');

  overlay.style.visibility = 'visible';
  dim.style.visibility = 'visible';

  dim.onclick = function() {
    overlay.style.visibility = 'hidden';
    dim.style.visibility = 'hidden';
  };
}

Alternatively, you could also add a click event listener to document and then determine whether event.target is the #overlay element.

For instance, the following would work (live example):

document.addEventListener('click', function (event) {
  var overlay = document.getElementById('overlay');
  var dim = document.getElementById('dim');

  if (event.target !== overlay && !event.target.closest('#overlay')) {
    overlay.style.visibility = 'hidden';
    dim.style.visibility = 'hidden';
  }
});
0

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.