简体   繁体   中英

click to show div, click again to hide, or click outside the div to hide

i have managed to make a script that allows me to show and hide my div when i click a link, but i also want it to hide the div when i click outside the div.... how do i manage such thing?

<script>
function toggle() {

var ele = document.getElementById("dropdown");

var text = document.getElementById("trigger");

if(ele.style.display == "block") {

        ele.style.display = "none";

    text.innerHTML = "Kontakta oss";

}

 else {

    ele.style.display = "block";

    text.innerHTML = "Kontakta oss";

}

 } 
    </script>

You need to listen to clicks on the document.

var ele = document.getElementById("dropdown");

document.addEventListener("click", function(event){ 
  var childClicked = [].slice.call(ele.getElementsByTagName('*')).some(function(node) {
    return node === event.target;
  });
  if(event.target !== ele && !childClicked){
      ele.style.display = "none";
  } 
});

I am using document here but you can choose whatever fits your needs with document.querySelector for example.

edit:after comment

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM