ezmilhouse
ezmilhouse

Reputation: 9121

let div disappear, onClick "everywhere but ..."

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

Upvotes: 3

Views: 1722

Answers (4)

adeneo
adeneo

Reputation: 318212

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

FIDDLE

Upvotes: 0

Nicola Peluchetti
Nicola Peluchetti

Reputation: 76880

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

Upvotes: 1

Alex
Alex

Reputation: 6406

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.

Upvotes: 0

Marius Ilie
Marius Ilie

Reputation: 3323

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

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

you could also try this.

Upvotes: 3

Related Questions