View Full Version : Closing Div Layer on body click

11-16-2011, 01:12 PM
I had implement a div layer that will close onClick on a image

function myDiv()

if(document.getElementById(myDiv').style.display == 'none' )

document.getElementById('myDiv').style.display = 'block';
document.getElementById('myDiv').style.display = 'none' ;

This is working fine, actually i want to display div layer as it is but need to close that div layer when i click any where else in the body. How can i implement this thing?

11-16-2011, 03:30 PM
but need to close that div layer when i click any where else in the body

I presume you mean any element other than the DIV.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">

<script type="text/javascript">

function myDiv(){
var obj=document.getElementById('myDiv'),e=window.event||arguments.callee.caller.arguments[0],eobj=e.target?e.target:e.srcElement;
while (eobj.parentNode){
if (eobj==obj){
return false;
obj.style.display=obj.style.display == 'none'?'block':'none'

function Init(){
document.body.onclick=function(){ myDiv(); }

if (window.addEventListener){
window.addEventListener('load',Init, false);
else if (window.attachEvent){


<body bgcolor="green">
<div id="myDiv" style="width:200px;height:200px;background-Color:red;" ></div>
<div style="width:200px;height:200px;background-Color:blue;" ></div>