Close an item when clicked anywhere on the page

I have an element on my page that turns on and off by clicking on a text link. I also need an element to hide when the user clicks "ANYWHERE" on the page outside the element itself - this is my jQuery code - can someone please show me what changes I need to make?

$(function() { $("#header-translate ul li").click(function() { $("#header-translate li ul").toggle("slide", { direction: "up" }, 500); }); }); 
+6
source share
6 answers

Usage The jQuery one function is perfect for this.

 $(function() { $("#header-translate ul li").click(function(e) { e.preventDefault(); var $toClose = $("#header-translate li ul") $toClose.slideToggle(500, function() { if($toClose.is(':visible')) { $('body').one('click', function(e) { e.preventDefault(); $toClose.slideUp(500); }); } else { $('body').unbind('click'); } }); }); }); 

To do this, make sure that this click handler will only start once and only when this element is shown.

+5
source

I believe that you need to add a click() handler to $('body') as well as event.stopPropagation() to your element.

 $(function() { $("#header-translate ul li").click(function(e) { // don't forget that 'e' $("#header-translate li ul").toggle("slide", { direction: "up" }, 500); e.stopPropagation(); // so this doesn't register as a body click }); $("body").click(function(e) { $("#header-translate").hide(); }); }); 
+2
source

Do you want to check

 $(function() { var elToHideSelector = "#header-translate li ul"; $("body").click(function(e) { if ( ! $(e.target).is(elToHideSelector + ',' + elToHideSelector + ' *') ) { $(elToHideSelector).hide(); } }); }); 
+1
source

I used this code:

  $(function() { $("#header-translate ul li").click(function(e) { $("#header-translate li ul").toggle("slide", { direction: "up" }, 500); e.stopPropagation(); // so this doesn't register as a body click }); $("body").click(function(e) { if ($('#header-translate li ul').is(':visible')) { $("#header-translate li ul").hide("slide", { direction: "up" }, 500);} }); }); 
+1
source

Add a click handler to the BODY tag, which moves the element up and adds event.stopPropagation () to the element that opens the element first, so the click to open is not sent to BODY.

0
source

You can add a listener to the document (since the event is bubbling up, you can write it to the parent)

 $(function() { $("#header-translate ul li").click(function() { $("#header-translate li ul").toggle("slide", { direction: "up" }, 500); $(document).one('click', function(){ $("#header-translate li ul").hide(); }); }); }); 
0
source

Source: https://habr.com/ru/post/896497/


All Articles