0

I am trying to make a "form" only visible after clicking another "button" with the following conditions:

  • The "form" should only be visible if you click the "button".
  • If you click either "outside" the form or click again the button: the form will become hidden again.

/* JAVASCRIPT */
const outer = document.getElementById('outer');
const inner = document.getElementById('inner')
outer.onclick = function() {
  if (inner.style.visibility == 'visible') {
    document.getElementById('inner').style.visibility = 'hidden';
  } else {
    document.getElementById('inner').style.visibility = 'visible';
  }
}
const ignoreClickOnMeElement = document.getElementById('inner');
document.addEventListener('click', function(event) {
  const isClickInsideElement = ignoreClickOnMeElement.contains(event.target);
  if (!isClickInsideElement) {
    // when uncommenting the line below everything stop working, rather then just closing if I click outside this div
    /*    document.getElementById('inner').style.visibility='hidden';*/
  }
});
/* CSS */

* {
  border: thin solid black;
}
<!-- HTML -->

<body>
  <div class="outer" id="outer">
    <button>Visible</button>
  </div>
  <div class="inner" id="inner" style="visibility: hidden;">
    <form id="form">
      <input type="number">
      <input type="number">
    </form>
  </div>
</body>
Pro Girl
  • 762
  • 7
  • 21
  • Just an idea... have you tried to add a listener to the body or whole document? In that listener event you have to check which element (target) has been hit and if it's not your form you will hide the form div. – HR123 Jan 16 '21 at 15:20

1 Answers1

1

If you use a delegated event listener bound to a higher node, such as the document body in this case you can determine which elements have been clicked based upon the event target.

let form=document.getElementById('form');
let bttn=document.querySelector('div.outer button');

document.body.addEventListener('click',e=>{

  e.preventDefault();
  e.stopPropagation();

  if( ( e.target==bttn && form.parentNode.style.visibility!=='visible' ) || e.target==form || e.target.parentNode==form ){
    form.parentNode.style.visibility='visible'
  }else{
    form.parentNode.style.visibility='hidden'
  }
  

})
* {
    border: thin solid black;
}
form{
  height:100px;width:80%;background:pink
}
.inner{
  height:200px;width:100%;
}
.outer{
  width:100%;height:100px;
}
<div class="outer" id="outer">
  <button>Visible</button>
</div>
<div class="inner" id="inner" style="visibility: hidden;">
  <form id="form">
    <input type="number">
    <input type="number">
  </form>
</div>
Professor Abronsius
  • 33,063
  • 5
  • 32
  • 46