Ad

Combining A Toggle Function With Another Function

- 1 answer

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
Ad

Answer

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

Ad
source: stackoverflow.com
Ad