Rectangle 27 0

javascript Hide Div onclick outside?


var mouse_out;
mydiv.onmouseover = function(){ mouse_out = false }; // mouse is over div
mydiv.onmouseout = function(){ mouse_out = true }; // mouse outside
document.onclick = function(){
   if(mouse_out)
      hideDiv(),   // hides mydiv
      document.onclick = null; // disables next clicks on document
};

Sign up for our newsletter and get our top new questions delivered to your inbox (see an example).

By far the best method I've seen. Most require juggling dynamic events as they happen -- this tracks the state of the div and takes action based on that state, not some other action. I use a slight variant; I track the state of the div by adding and removing a class instead of a variable. This makes it easier to track status on multiple divs and more easily handle complex logic that changes the state. But the core pattern is the same.

It works on every browser I tested, also IE 5. (IE4 and NS4 I don't know)

Just found an easy solution using onmouseover / out event handler.

hideDiv() function is called only if variable mouse_out is true.

Note
Rectangle 27 0

javascript Hide Div onclick outside?


div#overlay{
  position: fixed;
  width: 100%;
  height: 100%;
  background-image:url('transparent.gif');
  z-index: 1;
}
overlay

@Dampe Yes, thank you. Changed the code a bit for clarity.

Can you paste the code for the onclick event handler? I am experimenting with the code below. But the div closes when I click on it. function monitorClick(e){var evt = (e)?e:event; var theElem=(evt.srcElement)?evt.srcElement:evt.target; if(theElem.className == "form"){if(document.getElementById('mydiv').style.visibility = 'hidden') {document.getElementById('mydiv').style.visibility ='visible';} else{document.getElementById('mydiv').style.visibility = 'hidden';}}else if(theElem.id != "mydiv"){document.getElementById('mydiv').style.visibility = 'hidden';}} document.onclick = monitorClick;

I am not sure, but wouldn't be background:transparent; enough (instead using transparent image)? I haven't tested that of course, I am just curious.

Probably, but I think a transparent image would be more stable, just to maintain cross-browser compatibility.

The way I handled those kind of things in the past is create a transparent layer behind the div (use a BG image that is completely transparent) which has CSS somewhere along the lines of:

This div is of course only "visible" when the Div on top is visible. and then attach an onclick event handler to hide again.

Note