Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Close Element when clicking anywhere on page

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); 
});
});
like image 587
Zach Nicodemous Avatar asked Sep 02 '11 13:09

Zach Nicodemous


People also ask

How do I hide a div by clicking anywhere on the page?

$(document). click(function (event) { $('#myDIV:visible'). hide(); });

How do I stop pop ups when I click anywhere?

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.

How do you trigger an event when clicking outside the Element?

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.


1 Answers

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.

like image 89
Adam Terlson Avatar answered Sep 28 '22 04:09

Adam Terlson