javascript - jQuery: hide() box when clicking on body but not() on element itself? -


i have <a href="#" id="btn">show box</a> somwhere in dom. additionally have div#overlay default set display:none;.

// toggle overlay $('#btn').click(function(e) {     e.preventdefault();     $('#overlay').toggle(); })  $('body').not('#btn, #overlay').click(function() {     if ( $('#overlay').is(':visible') ) $('#overlay').hide(); }); 

why not working? want #btn toggle() overlay when clicking it. when overlay visible , click anywhere on document (except #btn or #overlay) want overlay hidden.

you capturing click on body never #btn or #overlay, , not work expected. need check against instead event.target

i.e.

$('body').click(function(e) {     var target = $(e.target);     if(!target.is('#btn') && !target.is('#overlay')) {        if ( $('#overlay').is(':visible') ) $('#overlay').hide();     } }); 

Comments

Popular posts from this blog

get url and add instance to a model with prefilled foreign key :django admin -

css - Make div keyboard-scrollable in jQuery Mobile? -

ruby on rails - Seeing duplicate requests handled with Unicorn -