0

I can't seem to find a proper way to combine these two functions into one. Both functions work, but when combined/or loaded together...it doesn't work.

Function:1 (standard toggle function)

$(document).ready(function(){
   $("#myButton").click(function(){
      $("#myDiv").toggle();
   });
});

Function:2 (click anywhere, except on the div, to hide it)

$(document).click(function(event) { 
   if(!$(event.target).closest('#myDiv').length) {
      if($('#myDiv').is(":visible")) {
         $("#myDiv").hide();
      }
   }        
})

What I want to achieve is this:

  1. if div hidden --> show div when clicked on button
  2. if div visible --> hide div when clicked anywhere, except on the div
zer00ne
  • 41,936
  • 6
  • 41
  • 68
Richard Avalos
  • 555
  • 5
  • 18

1 Answers1

1

Use one event handler, and do different things

$(document).on('click', function(event) { 
   if ( $(event.target).closest('#myButton').length ) {
        $("#myDiv").toggle();
   } else if( $('#myDiv').is(":visible") && $(event.target).closest('#myDiv').length === 0) {
        $("#myDiv").hide();
   }
});

FIDDLE

adeneo
  • 312,895
  • 29
  • 395
  • 388