I have an element on my page that is toggled on and off by clicking on a text link. I also need the element to hide when a user clicks ANYWHERE on the page outside of the element itself - this is my jQuery code - can someone please show me what modifications to make to do what I need?
$(function() {
$("#header-translate ul li").click(function() {
$("#header-translate li ul").toggle("slide", { direction: "up" }, 500);
});
});
$(document). click(function (event) { $('#myDIV:visible'). hide(); });
To close the popup the user will have to click a cross X in the corner of the popup. I need to edit the plugin so that the user can click ANYWHERE, and the plugin will close. Here is the javascript code I found.
Answer: Use the event. target Property You can use the event. target property to detect a click outside of an element such as dropdown menu. This property returns the DOM element that initiated the event.
Using jQuery's 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');
}
});
});
});
What this will do is assure that this click handler will only get executed once, and only when the element is shown.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With