How to close an element when a click is executed everywhere except an open element?

I am trying to make a panel that opens when she clicks on a button. I have a button, I have a panel. With the click() event, it opens. When this button is pressed again, it closes.

 $('#button').click(function() { $('#panel').toggle(); }); 

I want to achieve this if the user clicks everywhere except #button or #panel , it also closes.

PS I tried something similar, but this is not the desired behavior.

 $('#button').mouseenter(function() { $('#panel').show(); }).mouseleave(function() { setTimeout(function() { $('#panel').hide(); }, 2000); }); 
+4
source share
4 answers
 $( function(){ $("#button").click( function(){ $("#panel").toggle(); } ); $(document).click( function(e){ var elm = jQuery(e.target); if(elm.is("#button") || elm.is("#panel") || elm.parents("#panel").length>0)return; $("#panel").hide(); }); } ); 

Example

Checks that the item that was pressed [ e.target ] was not

  • elm.is("#button") button elm.is("#button")
  • Panel elm.is("#panel")
  • Any panel element elm.parents("#panel").length>0
+4
source

try it

 $('#button').click(function(e) { $('#panel').toggle(); e.stopPropagation(); }); $('#panel').click(function(e) { e.stopPropagation(); }); $(document.body).click(function(e) { if($('#panel').is(":visible")){ $('#panel').hide(); } }); 
+3
source

A direct response to your request will be

 $('body').click(function(e) var starter = $(e.target); if ( starter.is('#button, #panel') || starter.closest('#panel').length > 0 ) return; setTimeout(function() { $('#panel').hide(); }, 2000); }) 

But when you see what you tried to do with the mouse, you might think of this more appropriate approach.

 $('#button').click(function() { $('#panel').show(); }); $('#panel').mousenter(function() { var closetimer = $(this).data('closetimer'); // retrieve the timer if it exists clearTimeout(closetimer); // and clear the timeout when we re-enter to cancel the closing }).mouseleave(function() { var closetimer = setTimeout(function() { $('#panel').hide(); }, 2000); $(this).data('closetimer', closetimer); // store the timer with the panel so we can cancel it if we need }); 
+1
source

You have an invisible element located behind a panel that occupies 100% of the screen (or page). This element will receive a click event that will close both panels.

It will also prevent a click to close the panel from starting any other actions on the rest of the site.

If you want, you can also make the layered element gray and translucent, which will give you the effect of distracting the rest of the site while displaying the panel. This effect is used quite often with the help of Javascript popup scripts, and you can do it almost for free, since you will still place a full-screen element; you just need to style it.

0
source

All Articles