0

I'v searching for a way to hide a toggling div which is already hidden by default. I want to hide the div if user click outside of it!

I tried this:

<script> 
  $(document).ready(function(){ 
     $("#tab").hide();
     $("#open_tab").on("click",function(){
        $("#tab").toggle();    
        $("*").on("mouseup",function(e){
              var clicked=$(this).attr("id");
              if(clicked !="tab"){
                 e.stopPropagation();
                 $("#tab").hide();
              }
             else {
                   e.stopPropagation();
             }
        });
     });
}); </script>

But i don't know what's wrong with my code. Please can anyone help?

Nishu Tayal
  • 20,106
  • 8
  • 49
  • 101
Stanley Amos
  • 222
  • 2
  • 8

2 Answers2

0

The toggle() jQuery function:

Display or hide the matched elements. (documentation)

So, you don't need any mouseup event. Just use toggle() function on click for #open_tab.

HTML

<div id="open_tab">Click</div>
<div id="tab">TOGGLE</div>

Javascript

$("#tab").hide();
$("#open_tab").on("click", function () {
    $("#tab").toggle();
});

JSFIDDLE

Ionică Bizău
  • 109,027
  • 88
  • 289
  • 474
0

Your mouseup event gets registered only on click event on open_tab. You should move this block outside of $("#open_tab").on("click",function(). Please try the following:

<script> 
  $(document).ready(function(){ 
     $("#tab").hide();
     $("#open_tab").on("click",function(){
        $("#tab").toggle();    
     });

     $("*").on("mouseup",function(e){
          var clicked=$(this).attr("id");
          if(clicked !="tab"){
              e.stopPropagation();
              $("#tab").hide();
          } else {
              e.stopPropagation();
          }
     });
}); 
</script>

Update: Here is a shorter version for you:

<script>
    $("#tab").hide();
    $(document).on('click', function (evt) {
        if (evt.target.id == 'open_tab') {
            $('#tab').toggle();
        } else if (evt.target.id != 'tab') {
            $('#tab').hide();
        }
    });
</script>
vee
  • 38,255
  • 7
  • 74
  • 78
  • I did it that way to only trigger when `#open_tab` is click so it would'nt affect other `click` events. Is there any way to do this only when `#opent_tab` is clicked? – Stanley Amos Jul 02 '13 at 19:16
  • @StanleyAmos, please see my updated script. – vee Jul 02 '13 at 21:18