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
Post a Comment