Jump to content

how to hide the div when clicked on rest of the page?


yaragallamurali

Recommended Posts

Hi

I have an absolute div on my html page. my requirement is when i click on the rest of the page (other than the absolute div) the div's display should become none. I mean the div should not be displayed.

 

How can i achieve this? any simple solution? Please help.

Link to comment
Share on other sites

Seems like it can be a little tricky if there is a lot of clutter...

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>test</title>
<style>
#outer{
position:relative;
border:1px dotted green;
height:500px;
}
#inner{
position:absolute;
background-color:red;
border:1px dotted red;
top:100px;
left:100px;
right:100px;
bottom:100px;
}
#other1{
border:1px dotted orange;
height:400px;
width:50px;
}
#other2{
border:1px dotted green;
height:100px;
width:200px;
}
</style>
</head>

<body>

<div id="outer">

<div id="inner">
<div id="other2">
</div>
</div>  

<div id="other1">
</div>

</div>

<p>I want to hide the inner div if and only if the user clicks on the outer div.</p>
     
<script>
document.getElementById('outer').onclick = fout;

function fout(e){
  var i = e.target;
  var t = document.getElementById('inner');
  var inner = false;
  if (t.style.display != 'none'){
    while(i.tagName != 'BODY' && inner === false){
      if (i === t){
        inner = true;
      }
      i = i.parentElement;
    }
    if (inner === false){
      alert('hide inner');
      t.style.display = 'none';
    }
  }
}
</script>
     
</body>
</html>

Link to comment
Share on other sites

You know that 'inner' will be hidden using display: none; check against remaining elements that have parent 'outer' with that to cancel any action taken place.

            document.getElementById('outer').onclick = fout;
            function fout(event) {
                e = event || window.event;
                var t = document.getElementById('inner');

                if (t.style.display !== 'none' && e.target.id === 'outer') {
                    t.style.display = 'none';
                }
                else if (t.style.display === 'none' && e.target.id !== 'outer')
                {
                    return false;
                }
                else
                {
                    t.style.display = 'block';
                }

            }
Edited by dsonesuk
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...