Forum Moderators: open

Message Too Old, No Replies

Hide Div Question

         

Jon_King

7:32 pm on Jan 10, 2008 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



How can I hide a visible div by clicking outside of it? i.e. when someone clicks somewhere on their desktop outside the visible div I need it to close...

Dabrowski

8:16 pm on Jan 10, 2008 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



By clicking outside the div, do you mean outside the whole browser window, or somewhere else on the page? Or both?

Fotiman

8:53 pm on Jan 10, 2008 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



Here's one way using the Yahoo UI Library. Note, IE is has a bug where the underside of the div can be clicked and it will think it's not within that div. There is a fix, but I can't remember it off the top of my head.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset:utf-8">
<style type="text/css">
div {
margin: 1em;
padding: 1px;
border: 1px solid #000;
}
</style>
<title></title>
</head>
<body>
<div id="container">
<div>This is not it</div>
<div>This is not it</div>
<div>This is not it</div>
<div>This is not it</div>
<div>This is not it</div>
<div id='foo'>
<div>Click me</div>
<div>or me...
<div>or me!</div>
</div>
</div>
<div>This is not it</div>
<div>This is not it</div>
<div>This is not it</div>
<div>This is not it</div>
<div>This is not it</div>
</div>
<script type="text/javascript" src="http://yui.yahooapis.com/2.4.1/build/yahoo-dom-event/yahoo-dom-event.js"></script>
<script type="text/javascript">
YAHOO.util.Event.on(window, 'load', function() {
// Create some Shorthand variables:
var $E = YAHOO.util.Event;
var $D = YAHOO.util.Dom;
var foo = document.getElementById('foo');
$E.on(document.body, 'click', function(e) {
var n = $E.getTarget(e);
var anc;
// See if the event occured on or within 'foo'
if (n == foo) {
// The event occured on foo
// Do nothing
}
else {
anc = $D.getAncestorBy(n, function(el) {
return el == foo;
});
if (anc == null) {
// The event did not occur within 'foo' so hide it
$D.setStyle(foo, 'display', 'none');
}
}
});
});
</script>
</body>
</html>

[edited by: Fotiman at 8:53 pm (utc) on Jan. 10, 2008]