Jim Roboju
Jim Roboju

Reputation: 159

JavaScript lose focus

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.

Upvotes: 0

Views: 789

Answers (4)

Robert Swisher
Robert Swisher

Reputation: 1300

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
  }
}

Upvotes: 0

Sarfraz
Sarfraz

Reputation: 382746

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');
});

Upvotes: 2

Eugene
Eugene

Reputation: 2216

the raw js sample can be find here.

Upvotes: 0

Atul Dravid
Atul Dravid

Reputation: 1065

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

Upvotes: 0

Related Questions