tags:

views:

48

answers:

4

I have a div that is set to display:inline using the onclick() JS event handler. How do I make the div go back to display:none when I click any where else on the page other than the now visible div?

I've Googled about blur and setting the focus to another element but I don't know how to actually do it.

A: 

you can create an absolute div covering the whole window area by giving it 100% width and height and then give it an onclick to display:none your div. your div should have a z-index greater than the absolute div

aadravid
+2  A: 

If you want to use jQuery, it is easy:

$('*').click(function(){
  if ($(this).attr('id') !== 'div_id'){
     $('#div_id').css('display', 'none');
  }
});

The above becomes rather slow with all * selector, So I would recommend you to use jQuery Outside Events plugin.

Example:

$('#div_id').bind('clickoutside', function(){
  $(this).css('display', 'none');
});
Sarfraz
+1 for the link to the jQuery Outside Events plugin.
elo80ka
I don't really want to use jQuery, but I didn't specify so you win.
Jim Roboju
@Roboju: Then I hope you find a solution in vanilla javascript soon :)
Sarfraz
A: 

the raw js sample can be find here.

Eugene
A: 
document.onclick = function(e) {
  if (!e) var e = window.event;
  if (e.target.id == 'the_id_of_your_div') {
    // Do something
  } else {
    // Do something else
  }
}
Swish
What does the html look like that uses this?
Jim Roboju
<div id='the_id_of_your_div'>Some text</div>The event will fire whenever there is a click anywhere on the page
Swish