3

I got a DIV positioned absolute above other elements on the page and I want it to disappear when clicked somewhere but NOT inside that absolute positioned div (or one of its child elements).

I'm using jQuery's event propagation ($(document).on(...)) for all click events on page.

I would like to have a generic solution, not white- or blacklists of tags, classes please.

I'm not looking for a 'put a transparent layer in between absolute DIV and other content' solution, that would be my last ressort workaround.

Thx

ezmilhouse
  • 8,933
  • 7
  • 29
  • 38
  • This page will probably help : http://stackoverflow.com/questions/152975/how-to-detect-a-click-outside-an-element – Rondel Mar 12 '12 at 14:27

4 Answers4

3
$('html').click(function() {
  //Hide whatever you want to hide
});

$('#your_div').click(function(e){
  e.stopPropagation();
});

you could also try this.

Community
  • 1
  • 1
Marius Ilie
  • 3,283
  • 2
  • 25
  • 27
1

You could use e.target to check what has been clicked

$(document).on("click", "*", function(e) {
   if(e.target.id !== 'yourdivid'){
      $('#yourdivid').hide();
   }
  //Hide whatever you want to hide
});

EDIT - if you also need to check for children elements you could do like this

$(document).on("click", "*", function(e) {
   //check if the target is your div or a child of your div
   if($(e.target).closest('div#yourdivid').length !== 1){
      $('#yourdivid').hide();
   }
  //Hide whatever you want to hide
});
Nicola Peluchetti
  • 76,206
  • 31
  • 145
  • 192
  • this doesn't work if you click on the body, you have to click on an element. http://jsfiddle.net/khKb5/1/ – Alex Mar 12 '12 at 14:31
0

http://jsfiddle.net/khKb5/

jQuery:

$(document).on("click", function(e) {
    if($(e.target).closest('#box').length != 1){
        $('#box').hide();
    }
});

This works also if you click somewhere directly on the body.

Alex
  • 6,276
  • 2
  • 20
  • 26
0
$(document).on('click', function(e) {
    if (!(e.target.id=='myID' || $(e.target).parents('#myID').length>0)) {
        //do something
    }
});

FIDDLE

adeneo
  • 312,895
  • 29
  • 395
  • 388
  • winner, because of choosing parents() instead of closest(), see http://jsperf.com/jquery-parents-vs-closest/2 – ezmilhouse Mar 12 '12 at 15:13