Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery: Close DIV by clicking anywhere apart from the DIV itself?

I have a div that slides down when a button is clicked, and I would like to slide up the div when a user:

  1. Clicks anwhere except within the DIV itself
  2. Click a close button within the div.

Currently I've got it to a stage where, you click an element with the class .panel-tab - it slides down the panel with ID #panel... click anywhere else it slides up....

Here is my code so far to get the DIV to open and close:

<script type="text/javascript">
$(document).ready(function(){

$('.panel-tab').click(function(e) {
  $("#panel").stop(true, true).slideToggle("slow");
  e.stopPropagation();
});

$("body").click(function () {
  $("#panel:visible").stop(true, true).slideUp("slow");
});});
</script>
like image 216
CodeyMonkey Avatar asked Jul 07 '11 11:07

CodeyMonkey


1 Answers

You could bind a click event to the document and check if the click event happend within that div or any children. If not, close it.

Plugin time!

(function($){
    $.fn.outside = function(ename, cb){
        return this.each(function(){
            var $this = $(this),
                self = this;

            $(document).bind(ename, function tempo(e){
                if(e.target !== self && !$.contains(self, e.target)){
                    cb.apply(self, [e]);
                    if(!self.parentNode) $(document.body).unbind(ename, tempo);
                }
            });
        });
    };
}(jQuery));

usage:

$('.panel-tab').outside('click', function() {
    $('#panel').stop(true, true).slideUp('slow');
});
like image 158
jAndy Avatar answered Oct 06 '22 03:10

jAndy