alias51
alias51

Reputation: 8648

How to hide div when clicked outside of element

I have the following div:

<div id="welcome-lightbox">
   <div id="content"></div>
</div>

I want to hide the div when the user clicks anywhere BUT inside the div. I thought the most elegant way to do this would be stopPropagation (http://api.jquery.com/event.stopPropagation/)

$(document).click(function(){
  $('#welcome-lightbox').hide();
  $('#welcome-lightbox-box').click(function(event){
    event.stopPropagation();
  });
});

However, this approach does not seem to work; the div still hides when clicked. Any ideas?

Upvotes: 1

Views: 1727

Answers (5)

adeneo
adeneo

Reputation: 318352

Attach a click handler to the document, and check if the click originated from within the element by using closest() :

$(document).on('click', function(e){
    if (! $(e.target).closest('#welcome-lightbox').length )
        $('#welcome-lightbox').hide();
});

checking the event.target ID would close the lightbox if any element inside the lightbox, other than the lightbox itself, was clicked.

Upvotes: 2

divyaSharma
divyaSharma

Reputation: 133

<div id="welcome-lightbox"></div>

var lightbox = document.querySelector('#welcome-lightbox');

document.addEventListener('click',function(e) {
  if(e.id != lightbox.id) {
    lightbox.style.visibility = 'hidden';
  }
},false);

Upvotes: 1

Kevin Bowersox
Kevin Bowersox

Reputation: 94499

Attach an event handler above the element and then check the target to see if the div was clicked.

$(document).click(function(e){
    var divId = "welcome-lightbox";
    if(e.target.id != divId){
        $("#" + divId).hide();
    }
});

JS Fiddle: http://jsfiddle.net/rG3AC/

Upvotes: 2

Nemesis02
Nemesis02

Reputation: 292

You could do this by making it a 2 layer application, the outer div which spans the entire screen, like an overlay, then your inner div. Have a click event on the inner div which stops the event propogation, but then an a click event on the outer div which closes, or hides, itself.

Upvotes: 0

PSL
PSL

Reputation: 123739

That is because you are registering the event only after the first click on the document and it gets hidden. So move your stop propagation event registration for the specific element outside of the document's click handler.

Try:

$(document).click(function(){
  $('#welcome-lightbox').hide();

});
$(function(){
  $('#welcome-lightbox').click(function(event){ //Also your selector may be wrong?
    event.stopPropagation();
  });
});

Demo

Or you could just do:

$(document).click(function(e){
    if(e.target.id !== 'welcome-lightbox' )
        $('#welcome-lightbox').hide();
});

Upvotes: 4

Related Questions