Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

hide div when click outside

Tags:

javascript

I am using a simple javascript code to toggle div onclick. You can see it in action on this link: k-prim.biz/Untitled-2.html - it is a quite simple demo page. What I want to make is to hide div not only when click on the "link" but also when click outside the div. Also how can I change the css style of the "link" when the div is displayed? Thank you in advance!

<script type="text/javascript" language="javascript"> 
   function showHide() {
   var ele = document.getElementById("showHideDiv");
if(ele.style.display == "block") {
        ele.style.display = "none";
  }
else {
    ele.style.display = "block"; }
}
</script> 
<a href="#" onClick="return showHide();" >link</a>
<div id="showHideDiv" style="display:none;">hello!</div>    
like image 606
Ljubo Valevski Avatar asked Jan 14 '23 08:01

Ljubo Valevski


1 Answers

You've not given me any code to work with, so you'll have to modify this to suit your needs:

$(document).click(function() {
    if(this != $("#the_div")[0]) {
        $("#the_div").hide();
    }
});

That will hide the div if a user clicks anywhere on the page that isn't that div.

like image 106
Elliot Bonneville Avatar answered Jan 16 '23 20:01

Elliot Bonneville