Search code examples
javascripttogglebutton

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>

Solution

  • 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