Alex Rivera | Logout

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

Asked 2011-07-07T11:41:50.327
16

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>
Edit
Report

1 Answer

1

i would do something like this

var $doc, $panel = $('.panel-tab');
$doc = $(document);
$doc.bind("click", function(){
   $panel.hide();
   $doc.undbind("click");
});

$panel.bind("click", function(e){
   e.stopPropagation();
});

you always close the tab on the click on the document, but you stop the event from propagation on the tab it self.

here a working example: http://jsfiddle.net/meo/TnG4E/

answered 2011-07-07T12:16:38.460

Your Answer