Let the div disappear, onClick "everywhere, but ..."

I got a DIV positioned 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 children).

I am using jQuery event propagation ($ (document) .on (...)) for all click events on the page.

I would like to have a generic solution, not whitelisted or blacklisted tags, please.

I am not looking for "set transparent layer between absolute DIV and other content", this would be my last temporary solution.

thank

+3


source to share


4 answers


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

      



FIDDLE

0


source


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

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

      



you can also try this .

+3


source


You can use e.target to check what was 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 items you can do 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
});

      

+1


source


http://jsfiddle.net/khKb5/

JQuery

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

      

It also works if you click anywhere directly on body

.

0


source







All Articles