text:
Q: How to bind an object to the label in c# windows forms I have  labels with footballer's names inside. I want to get footballer's age after clicking on these labels. I do it by this way:
public partial class Form1 : Form
{
    Footballer[] team = { /*team initialization*/};
    public Form1()
    {
        InitializeComponent();
    }
    private void OnLabel_Click(object sender, EventArgs e)
    {
        for (int i = 0; i < team.Length; i++)
        {
            if (team[i].Name == this.Text)
            {
                MessageBox.Show(team[i].Age.ToString());
                break;
            }
        }
    }
}

But there is problem. There might be more than one player with the same name. So I want to bind each label with footballer. How can I do this?

A: For sake of simplicity suppose that you initialize your labels in this mode....
public Form1()
{
    InitializeComponent();
    int index = 0;
    foreach(Label lbl in this.Controls.OfType<Label>())
    {
        lbl.Text = team[index].Name;

        // Make the Tag property reference the Footballer instance
        // used to set the label text with the footballer name
        lbl.Tag = team[index];
        index++;
    }

At this point, when you receive the click event, you just need to retrieve the reference from the Tag property and use it directly
    private void OnLabel_Click(object sender, EventArgs e)
    {
        // No loop needed here
        Label current = sender as Label;
        Footballer player = current.Tag as Footballer;
        if(player != null)
            MessageBox.Show(player.Age.ToString());
    }
}

A: You should separate out your business logic from your presentation logic.  The name is what you presented, but to keep each player/team unique then assign a unique ID.
This is then assigned to the label but hidden from view, so that when the label is clicked the ID is retrieved and you can then do a lookup based on this.
So with Player class like the following:
public class Player
{
   public int ID { get;set; }
   public string Name { get;set; }
   //etc.
}

Then when assigning a Player to label use Label.Tag which is a general purpose field which you can use for anything your want. (Available on all Controls).
label1.Text = MyPlayer.Name;
label1.Tag = MyPlayer.ID;

If I was you, I would also change your Teams to be a List not an array
List<Footballer> team = new List<Footballer>() { /*team initialization*/};

Then you can look up as follows
private void OnLabel_Click(object sender, EventArgs e)
{
      Label clickedLabel = (sender as Label);
      int id = Convert.ToInt32(clickedLabel.Tag);
      Footballer found = team.Find(x => x.Id == id);
      MessageBox.Show(found.Age.ToString());
}


text:
Q: Android Studio Assets Folder Missing I am trying to add an assets folder in Android Studio but it is not an option to me.  When I go into the android view and try to create a new folder I am only presented with these options.

An alternative answer I found was to go to the packages view; however, I could not see my project directory from there.  Does anyone know a way to add it as an option?  Thanks!

A: Right-click on app folder go to New> Folder>Assets Folder.
Android Studio will open a dialog box.  Keep all the settings default. Under the target source set, option main should be selected. and click finish.

A: I resolved the issue.  My gradle file was not updated and I needed to sync dependencies.  Once doing that I was presented with the option to create an assets folder.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Why can `unquote` be called outside a macro? h unquote says it "Unquotes the given expression from inside a macro."
However, I've just seen a way that unquote can be used outside a macro.
defmodule Example do
  x = 4
  def foo do
    unquote(x)
  end

  x = 5
  def bar do
    x = 4
    "#{unquote(x)}, #{x}"
  end
end

IO.puts Example.foo #=> 4
IO.puts Example.bar #=> "5, 4"

Is this the same unquote, or a different one? Is this a feature or a bug? (It seems to overlap with the "temporary storage" purpose of module attributes.)
Why can I call unquote outside a macro quote?

A: This works because def itself is a macro implemented with defmacro and returns a quoted expression. So whilst it appears you are not inside of a quoted expression as you don't call quote, you actually are.
https://github.com/elixir-lang/elixir/blob/928302a912e397917be957142a9837ae58610207/lib/elixir/lib/kernel.ex#L3225L3227
There are other places where this holds true, for example inside ExUnit tests (again because the test macro uses def to define a function. https://github.com/elixir-lang/elixir/blob/928302a912e397917be957142a9837ae58610207/lib/ex_unit/lib/ex_unit/case.ex#L256

A: The simplest answer is that everything in a module is inside an implicit quote.
In particular this is done in the definition of defmodule (which is just a regular macro): https://github.com/elixir-lang/elixir/blob/master/lib/elixir/lib/kernel.ex#L3008
Why is this needed? Elixir compiler works on the AST and the only way to get an AST is to quote the code.
Disclaimer: This is my understanding of what's happening. The truth about why it's done like this might be different.


text:
Q: How do I detect a click outside an element? I have some HTML menus, which I show completely when a user clicks on the head of these menus. I would like to hide these elements when the user clicks outside the menus' area.
Is something like this possible with jQuery?
$("#menuscontainer").clickOutsideThisElement(function() {
    // Hide the menus
});

A: If you are scripting for IE and FF 3.* and you just want to know if the click occured within a certain box area, you could also use something like:

this.outsideElementClick = function(objEvent, objElement) {
  var objCurrentElement = objEvent.target || objEvent.srcElement;
  var blnInsideX = false;
  var blnInsideY = false;

  if (objCurrentElement.getBoundingClientRect().left >= objElement.getBoundingClientRect().left && objCurrentElement.getBoundingClientRect().right <= objElement.getBoundingClientRect().right)
    blnInsideX = true;

  if (objCurrentElement.getBoundingClientRect().top >= objElement.getBoundingClientRect().top && objCurrentElement.getBoundingClientRect().bottom <= objElement.getBoundingClientRect().bottom)
    blnInsideY = true;

  if (blnInsideX && blnInsideY)
    return false;
  else
    return true;
}

A: Instead using flow interruption, blur/focus event or any other tricky technics, simply match event flow with element's kinship:
$(document).on("click.menu-outside", function(event){
    // Test if target and it's parent aren't #menuscontainer
    // That means the click event occur on other branch of document tree
    if(!$(event.target).parents().andSelf().is("#menuscontainer")){
        // Click outisde #menuscontainer
        // Hide the menus (but test if menus aren't already hidden)
    }
});

To remove click outside event listener, simply:
$(document).off("click.menu-outside");

A: If someone curious here is javascript solution(es6):
window.addEventListener('mouseup', e => {
        if (e.target != yourDiv && e.target.parentNode != yourDiv) {
            yourDiv.classList.remove('show-menu');
            //or yourDiv.style.display = 'none';
        }
    })

and es5, just in case:
window.addEventListener('mouseup', function (e) {
if (e.target != yourDiv && e.target.parentNode != yourDiv) {
    yourDiv.classList.remove('show-menu');
    //or yourDiv.style.display = 'none';
}

});

A: Use:
var go = false;
$(document).click(function(){
    if(go){
        $('#divID').hide();
        go = false;
    }
})

$("#divID").mouseover(function(){
    go = false;
});

$("#divID").mouseout(function (){
    go = true;
});

$("btnID").click( function(){
    if($("#divID:visible").length==1)
        $("#divID").hide(); // Toggle
    $("#divID").show();
});

A: Hook a click event listener on the document. Inside the event listener, you can look at the event object, in particular, the event.target to see what element was clicked:
$(document).click(function(e){
    if ($(e.target).closest("#menuscontainer").length == 0) {
        // .closest can help you determine if the element
        // or one of its ancestors is #menuscontainer
        console.log("hide");
    }
});

A: Here is a simple solution by pure javascript. It is up-to-date with ES6:
var isMenuClick = false;
var menu = document.getElementById('menuscontainer');
document.addEventListener('click',()=>{
    if(!isMenuClick){
       //Hide the menu here
    }
    //Reset isMenuClick
    isMenuClick = false;
})
menu.addEventListener('click',()=>{
    isMenuClick = true;
})

A: I have used below script and done with jQuery.
jQuery(document).click(function(e) {
    var target = e.target; //target div recorded
    if (!jQuery(target).is('#tobehide') ) {
        jQuery(this).fadeOut(); //if the click element is not the above id will hide
    }
})

Below find the HTML code

 Hello I am the title

I will hide when you click outside of me

You can read the tutorial here

A: After research, I have found three working solutions
First solution

Second solution

Third solution

A: $(document).click(function() {
    $(".overlay-window").hide();
});
$(".overlay-window").click(function() {
    return false;
});

If you click on the document, hide a given element, unless you click on that same element.

A: I did it like this in YUI 3:
// Detect the click anywhere other than the overlay element to close it.
Y.one(document).on('click', function (e) {
    if (e.target.ancestor('#overlay') === null && e.target.get('id') != 'show' && overlay.get('visible') == true) {
        overlay.hide();
    }
});

I am checking if ancestor is not the widget element container,
if target is not which open the widget/element,
if widget/element I want to close is already open (not that important).

A: We implemented a solution, partly based off a comment from a user above, which works perfectly for us. We use it to hide a search box / results when clicking outside those elements, excluding the element that originally.
// HIDE SEARCH BOX IF CLICKING OUTSIDE
$(document).click(function(event){
    // IF NOT CLICKING THE SEARCH BOX OR ITS CONTENTS OR SEARCH ICON
    if ($("#search-holder").is(":visible") && !$(event.target).is("#search-holder *, #search")) {
        $("#search-holder").fadeOut('fast');
        $("#search").removeClass('active');
    }
});

It checks if the search box is already visible first also, and in our case, it's also removing an active class on the hide/show search button.

A: Upvote for the most popular answer, but add
&& (e.target != $('html').get(0)) // ignore the scrollbar

so, a click on a scroll bar does not [hide or whatever] your target element.

A: For easier use, and more expressive code, I created a jQuery plugin for this:
$('div.my-element').clickOut(function(target) {
    //do something here...
});

Note:  target is the element the user actually clicked.  But callback is still executed in the context of the original element, so you can utilize this as you'd expect in a jQuery callback.
Plugin:
$.fn.clickOut = function (parent, fn) {
    var context = this;
    fn = (typeof parent === 'function') ? parent : fn;
    parent = (parent instanceof jQuery) ? parent : $(document);

    context.each(function () {
        var that = this;
        parent.on('click', function (e) {
            var clicked = $(e.target);
            if (!clicked.is(that) && !clicked.parents().is(that)) {
                if (typeof fn === 'function') {
                    fn.call(that, clicked);
                }
            }
        });

    });
    return context;
};

By default, the click event listener is placed on the document.  However, if you want to limit the event listener scope, you can pass in a jQuery object representing a parent level element that will be the top parent at which clicks will be listened to.  This prevents unnecessary document level event listeners.  Obviously, it won't work unless the parent element supplied is a parent of your initial element.
Use like so:
$('div.my-element').clickOut($('div.my-parent'), function(target) {
    //do something here...
});

A: $("#menuscontainer").click(function() {
    $(this).focus();
});
$("#menuscontainer").blur(function(){
    $(this).hide();
});

Works for me just fine.

A:
How to detect a click outside an element?

The reason that this question is so popular and has so many answers is that it is deceptively complex. After almost eight years and dozens of answers, I am genuinely surprised to see how little care has been given to accessibility.

I would like to hide these elements when the user clicks outside the menus' area.

This is a noble cause and is the actual issue. The title of the question—which is what most answers appear to attempt to address—contains an unfortunate red herring.
Hint: it's the word "click"!
You don't actually want to bind click handlers.
If you're binding click handlers to close the dialog, you've already failed. The reason you've failed is that not everyone triggers click events. Users not using a mouse will be able to escape your dialog (and your pop-up menu is arguably a type of dialog) by pressing Tab, and they then won't be able to read the content behind the dialog without subsequently triggering a click event.
So let's rephrase the question.

How does one close a dialog when a user is finished with it?

This is the goal. Unfortunately, now we need to bind the userisfinishedwiththedialog event, and that binding isn't so straightforward.
So how can we detect that a user has finished using a dialog?
focusout event
A good start is to determine if focus has left the dialog.
Hint: be careful with the blur event, blur doesn't propagate if the event was bound to the bubbling phase!
jQuery's focusout will do just fine. If you can't use jQuery, then you can use blur during the capturing phase:
element.addEventListener('blur', ..., true);
//                       use capture: ^^^^

Also, for many dialogs you'll need to allow the container to gain focus. Add tabindex="-1" to allow the dialog to receive focus dynamically without otherwise interrupting the tabbing flow.

$('a').on('click', function () {
  $(this.hash).toggleClass('active').focus();
});

$('div').on('focusout', function () {
  $(this).removeClass('active');
});
div {
  display: none;
}
.active {
  display: block;
}

Example

  Lorem ipsum dolor sit amet.

If you play with that demo for more than a minute you should quickly start seeing issues.
The first is that the link in the dialog isn't clickable. Attempting to click on it or tab to it will lead to the dialog closing before the interaction takes place. This is because focusing the inner element triggers a focusout event before triggering a focusin event again.
The fix is to queue the state change on the event loop. This can be done by using setImmediate(...), or setTimeout(..., 0) for browsers that don't support setImmediate. Once queued it can be cancelled by a subsequent focusin:
$('.submenu').on({
  focusout: function (e) {
    $(this).data('submenuTimer', setTimeout(function () {
      $(this).removeClass('submenu--active');
    }.bind(this), 0));
  },
  focusin: function (e) {
    clearTimeout($(this).data('submenuTimer'));
  }
});

$('a').on('click', function () {
  $(this.hash).toggleClass('active').focus();
});

$('div').on({
  focusout: function () {
    $(this).data('timer', setTimeout(function () {
      $(this).removeClass('active');
    }.bind(this), 0));
  },
  focusin: function () {
    clearTimeout($(this).data('timer'));
  }
});
div {
  display: none;
}
.active {
  display: block;
}

Example

  Lorem ipsum dolor sit amet.

The second issue is that the dialog won't close when the link is pressed again. This is because the dialog loses focus, triggering the close behavior, after which the link click triggers the dialog to reopen.
Similar to the previous issue, the focus state needs to be managed. Given that the state change has already been queued, it's just a matter of handling focus events on the dialog triggers:
This should look familiar
$('a').on({
  focusout: function () {
    $(this.hash).data('timer', setTimeout(function () {
      $(this.hash).removeClass('active');
    }.bind(this), 0));
  },
  focusin: function () {
    clearTimeout($(this.hash).data('timer'));
  }
});

$('a').on('click', function () {
  $(this.hash).toggleClass('active').focus();
});

$('div').on({
  focusout: function () {
    $(this).data('timer', setTimeout(function () {
      $(this).removeClass('active');
    }.bind(this), 0));
  },
  focusin: function () {
    clearTimeout($(this).data('timer'));
  }
});

$('a').on({
  focusout: function () {
    $(this.hash).data('timer', setTimeout(function () {
      $(this.hash).removeClass('active');
    }.bind(this), 0));
  },
  focusin: function () {
    clearTimeout($(this.hash).data('timer'));
  }
});
div {
  display: none;
}
.active {
  display: block;
}

Example

  Lorem ipsum dolor sit amet.

Esc key
If you thought you were done by handling the focus states, there's more you can do to simplify the user experience.
This is often a "nice to have" feature, but it's common that when you have a modal or popup of any sort that the Esc key will close it out.
keydown: function (e) {
  if (e.which === 27) {
    $(this).removeClass('active');
    e.preventDefault();
  }
}

$('a').on('click', function () {
  $(this.hash).toggleClass('active').focus();
});

$('div').on({
  focusout: function () {
    $(this).data('timer', setTimeout(function () {
      $(this).removeClass('active');
    }.bind(this), 0));
  },
  focusin: function () {
    clearTimeout($(this).data('timer'));
  },
  keydown: function (e) {
    if (e.which === 27) {
      $(this).removeClass('active');
      e.preventDefault();
    }
  }
});

$('a').on({
  focusout: function () {
    $(this.hash).data('timer', setTimeout(function () {
      $(this.hash).removeClass('active');
    }.bind(this), 0));
  },
  focusin: function () {
    clearTimeout($(this.hash).data('timer'));
  }
});
div {
  display: none;
}
.active {
  display: block;
}

Example

  Lorem ipsum dolor sit amet.

If you know you have focusable elements within the dialog, you won't need to focus the dialog directly. If you're building a menu, you could focus the first menu item instead.
click: function (e) {
  $(this.hash)
    .toggleClass('submenu--active')
    .find('a:first')
    .focus();
  e.preventDefault();
}

$('.menu__link').on({
  click: function (e) {
    $(this.hash)
      .toggleClass('submenu--active')
      .find('a:first')
      .focus();
    e.preventDefault();
  },
  focusout: function () {
    $(this.hash).data('submenuTimer', setTimeout(function () {
      $(this.hash).removeClass('submenu--active');
    }.bind(this), 0));
  },
  focusin: function () {
    clearTimeout($(this.hash).data('submenuTimer'));
  }
});

$('.submenu').on({
  focusout: function () {
    $(this).data('submenuTimer', setTimeout(function () {
      $(this).removeClass('submenu--active');
    }.bind(this), 0));
  },
  focusin: function () {
    clearTimeout($(this).data('submenuTimer'));
  },
  keydown: function (e) {
    if (e.which === 27) {
      $(this).removeClass('submenu--active');
      e.preventDefault();
    }
  }
});
.menu {
  list-style: none;
  margin: 0;
  padding: 0;
}
.menu:after {
  clear: both;
  content: '';
  display: table;
}
.menu__item {
  float: left;
  position: relative;
}

.menu__link {
  background-color: lightblue;
  color: black;
  display: block;
  padding: 0.5em 1em;
  text-decoration: none;
}
.menu__link:hover,
.menu__link:focus {
  background-color: black;
  color: lightblue;
}

.submenu {
  border: 1px solid black;
  display: none;
  left: 0;
  list-style: none;
  margin: 0;
  padding: 0;
  position: absolute;
  top: 100%;
}
.submenu--active {
  display: block;
}

.submenu__item {
  width: 150px;
}

.submenu__link {
  background-color: lightblue;
  color: black;
  display: block;
  padding: 0.5em 1em;
  text-decoration: none;
}

.submenu__link:hover,
.submenu__link:focus {
  background-color: black;
  color: lightblue;
}

    Menu 1

Example 1

Example 2

Example 3

Example 4

    Menu 2

Example 1

Example 2

Example 3

Example 4

lorem ipsum dolor sit amet.

WAI-ARIA Roles and Other Accessibility Support
This answer hopefully covers the basics of accessible keyboard and mouse support for this feature, but as it's already quite sizable I'm going to avoid any discussion of WAI-ARIA roles and attributes, however I highly recommend that implementers refer to the spec for details on what roles they should use and any other appropriate attributes.

A: Function:
$(function() {
    $.fn.click_inout = function(clickin_handler, clickout_handler) {
        var item = this;
        var is_me = false;
        item.click(function(event) {
            clickin_handler(event);
            is_me = true;
        });
        $(document).click(function(event) {
            if (is_me) {
                is_me = false;
            } else {
                clickout_handler(event);
            }
        });
        return this;
    }
});

Usage:
this.input = $('<input>')
    .click_inout(
        function(event) { me.ShowTree(event); },
        function() { me.Hide(); }
    )
    .appendTo(this.node);

And functions are very simple:
ShowTree: function(event) {
    this.data_span.show();
}
Hide: function() {
    this.data_span.hide();
}

A: This should work:
$('body').click(function (event) {
    var obj = $(event.target);
    obj = obj['context']; // context : clicked element inside body
    if ($(obj).attr('id') != "menuscontainer" && $('#menuscontainer').is(':visible') == true) {
        //hide menu
    }
});

A: The solutions here work fine when only one element is to be managed. If there are multiple elements, however, the problem is much more complicated. Tricks with e.stopPropagation() and all the others will not work.
I came up with a solution, and maybe it is not so easy, but it's better than nothing. Have a look:
$view.on("click", function(e) {

    if(model.isActivated()) return;

        var watchUnclick = function() {
            rootView.one("mouseleave", function() {
                $(document).one("click", function() {
                    model.deactivate();
                });
                rootView.one("mouseenter", function() {
                    watchUnclick();
                });
            });
        };
        watchUnclick();
        model.activate();
    });

A: I ended up doing something like this:
$(document).on('click', 'body, #msg_count_results .close',function() {
    $(document).find('#msg_count_results').remove();
});
$(document).on('click','#msg_count_results',function(e) {
    e.preventDefault();
    return false;
});

I have a close button within the new container for end users friendly UI purposes. I had to use return false in order to not go through. Of course, having an A HREF on there to take you somewhere would be nice, or you could call some ajax stuff instead. Either way, it works ok for me. Just what I wanted.

A: I just want to make @Pistos answer more apparent since it's hidden in the comments.
This solution worked perfectly for me. Plain JS:
var elementToToggle = $('.some-element');
$(document).click( function(event) {
  if( $(event.target).closest(elementToToggle).length === 0 ) {
    elementToToggle.hide();
  }
});

in CoffeeScript:
elementToToggle = $('.some-element')
$(document).click (event) ->
  if $(event.target).closest(elementToToggle).length == 0
    elementToToggle.hide()

A: Let's say the div you want to detect if the user clicked outside or inside has an id, for example: "my-special-widget".
Listen to body click events:
document.body.addEventListener('click', (e) => {
    if (isInsideMySpecialWidget(e.target, "my-special-widget")) {
        console.log("user clicked INSIDE the widget");
    }
    console.log("user clicked OUTSIDE the widget");
});

function isInsideMySpecialWidget(elem, mySpecialWidgetId){
    while (elem.parentElement) {
        if (elem.id === mySpecialWidgetId) {
            return true;
        }
        elem = elem.parentElement;
    }
    return false;
}

In this case, you won't break the normal flow of click on some element in your page, since you are not using the "stopPropagation" method.

A: Now there is a plugin for that: outside events (blog post)
The following happens when a clickoutside handler (WLOG) is bound to an element:

*

*the element is added to an array which holds all elements with clickoutside handlers

*a (namespaced) click handler is bound to the document (if not already there)

*on any click in the document, the clickoutside event is triggered for those elements in that array that are not equal to or a parent of the click-events target

*additionally, the event.target for the clickoutside event is set to the element the user clicked on (so you even know what the user clicked, not just that he clicked outside)

So no events are stopped from propagation and additional click handlers may be used "above" the element with the outside-handler.

A: This worked for me perfectly!!
$('html').click(function (e) {
    if (e.target.id == 'YOUR-DIV-ID') {
        //do something
    } else {
        //do something
    }
});

A: This is my solution to this problem:
$(document).ready(function() {
  $('#user-toggle').click(function(e) {
    $('#user-nav').toggle();
    e.stopPropagation();
  });

  $('body').click(function() {
    $('#user-nav').hide();
  });

  $('#user-nav').click(function(e){
    e.stopPropagation();
  });
});

A: The answer marked as the accepted answer does not take into account that you can have overlays over the element, like dialogs, popovers, datepickers, etc. Clicks in these should not hide the element.
I have made my own version that does take this into account. It's created as a KnockoutJS binding, but it can easily be converted to jQuery-only.
It works by the first query for all elements with either z-index or absolute position that are visible. It then hit tests those elements against the element I want to hide if click outside. If it's a hit I calculate a new bound rectangle which takes into account the overlay bounds.
ko.bindingHandlers.clickedIn = (function () {
    function getBounds(element) {
        var pos = element.offset();
        return {
            x: pos.left,
            x2: pos.left + element.outerWidth(),
            y: pos.top,
            y2: pos.top + element.outerHeight()
        };
    }

    function hitTest(o, l) {
        function getOffset(o) {
            for (var r = { l: o.offsetLeft, t: o.offsetTop, r: o.offsetWidth, b: o.offsetHeight };
                o = o.offsetParent; r.l += o.offsetLeft, r.t += o.offsetTop);
            return r.r += r.l, r.b += r.t, r;
        }

        for (var b, s, r = [], a = getOffset(o), j = isNaN(l.length), i = (j ? l = [l] : l).length; i;
            b = getOffset(l[--i]), (a.l == b.l || (a.l > b.l ? a.l <= b.r : b.l <= a.r))
                && (a.t == b.t || (a.t > b.t ? a.t <= b.b : b.t <= a.b)) && (r[r.length] = l[i]));
        return j ? !!r.length : r;
    }

    return {
        init: function (element, valueAccessor) {
            var target = valueAccessor();
            $(document).click(function (e) {
                if (element._clickedInElementShowing === false && target()) {
                    var $element = $(element);
                    var bounds = getBounds($element);

                    var possibleOverlays = $("[style*=z-index],[style*=absolute]").not(":hidden");
                    $.each(possibleOverlays, function () {
                        if (hitTest(element, this)) {
                            var b = getBounds($(this));
                            bounds.x = Math.min(bounds.x, b.x);
                            bounds.x2 = Math.max(bounds.x2, b.x2);
                            bounds.y = Math.min(bounds.y, b.y);
                            bounds.y2 = Math.max(bounds.y2, b.y2);
                        }
                    });

                    if (e.clientX < bounds.x || e.clientX > bounds.x2 ||
                        e.clientY < bounds.y || e.clientY > bounds.y2) {

                        target(false);
                    }
                }
                element._clickedInElementShowing = false;
            });

            $(element).click(function (e) {
                e.stopPropagation();
            });
        },
        update: function (element, valueAccessor) {
            var showing = ko.utils.unwrapObservable(valueAccessor());
            if (showing) {
                element._clickedInElementShowing = true;
            }
        }
    };
})();

A: I know there are a million answers to this question, but I've always been a fan of using HTML and CSS to do most of the work. In this case, z-index and positioning. The simplest way that I have found to do this is as follows:

$("#show-trigger").click(function(){
  $("#element").animate({width: 'toggle'});
  $("#outside-element").show();
});
$("#outside-element").click(function(){
  $("#element").hide();
  $("#outside-element").hide();
});
#outside-element {
  position:fixed;
  width:100%;
  height:100%;
  z-index:1;
  display:none;
}
#element {
  display:none;
  padding:20px;
  background-color:#ccc;
  width:300px;
  z-index:2;
  position:relative;
}
#show-trigger {
  padding:20px;
  background-color:#ccc;
  margin:20px auto;
  z-index:2;
}

Menu Item 1

Menu Item 1

Menu Item 1

Menu Item 1

Show Menu

This creates a safe environment, since nothing is going to get triggered unless the menu is actually open and the z-index protects any of the content within the element from creating any misfires upon being clicked.
Additionally, you're not requiring jQuery to cover all of your bases with propagation calls and having to purge all of the inner elements from misfires.

A: Here is what I do to solve to problem.
$(window).click(function (event) {
    //To improve performance add a checklike
    //if(myElement.isClosed) return;
    var isClickedElementChildOfMyBox = isChildOfElement(event,'#id-of-my-element');

    if (isClickedElementChildOfMyBox)
        return;

    //your code to hide the element
});

var isChildOfElement = function (event, selector) {
    if (event.originalEvent.path) {
        return event.originalEvent.path[0].closest(selector) !== null;
    }

    return event.originalEvent.originalTarget.closest(selector) !== null;
}

A: If you are using tools like "Pop-up", you can use the "onFocusOut" event.

window.onload=function(){
document.getElementById("inside-div").focus();
}
function loseFocus(){
alert("Clicked outside");
}
#container{
background-color:lightblue;
width:200px;
height:200px;
}

#inside-div{
background-color:lightgray;
width:100px;
height:100px;

}

<input type="text" id="inside-div" onfocusout="loseFocus()">

A: All of these answers solve the problem, but I would like to contribute with a moders es6 solution that does exactly what is needed. I just hope to make someone happy with this runnable demo.

window.clickOutSide = (element, clickOutside, clickInside) => {
  document.addEventListener('click', (event) => {
    if (!element.contains(event.target)) {
      if (typeof clickInside === 'function') {
        clickOutside();
      }
    } else {
      if (typeof clickInside === 'function') {
        clickInside();
      }
    }
  });
};

window.clickOutSide(document.querySelector('.block'), () => alert('clicked outside'), () => alert('clicked inside'));
.block {
  width: 400px;
  height: 400px;
  background-color: red;
}

A: I don't think what you really need is to close the menu when the user clicks outside; what you need is for the menu to close when the user clicks anywhere at all on the page. If you click on the menu, or off the menu it should close right?
Finding no satisfactory answers above prompted me to write this blog post the other day. For the more pedantic, there are a number of gotchas to take note of:

*

*If you attach a click event handler to the body element at click time be sure to wait for the 2nd click before closing the menu, and unbinding the event. Otherwise the click event that opened the menu will bubble up to the listener that has to close the menu.

*If you use event.stopPropogation() on a click event, no other elements in your page can have a click-anywhere-to-close feature.

*Attaching a click event handler to the body element indefinitely is not a performant solution

*Comparing the target of the event, and its parents to the handler's creator assumes that what you want is to close the menu when you click off it, when what you really want is to close it when you click anywhere on the page.

*Listening for events on the body element will make your code more brittle. Styling as innocent as this would break it: body { margin-left:auto; margin-right: auto; width:960px;}

A: As another poster said there are a lot of gotchas, especially if the element you are displaying (in this case a menu) has interactive elements.
I've found the following method to be fairly robust:
$('#menuscontainer').click(function(event) {
    //your code that shows the menus fully

    //now set up an event listener so that clicking anywhere outside will close the menu
    $('html').click(function(event) {
        //check up the tree of the click target to check whether user has clicked outside of menu
        if ($(event.target).parents('#menuscontainer').length==0) {
            // your code to hide menu

            //this event listener has done its job so we can unbind it.
            $(this).unbind(event);
        }

    })
});

A: A simple solution for the situation is:
$(document).mouseup(function (e)
{
    var container = $("YOUR SELECTOR"); // Give you class or ID

    if (!container.is(e.target) &&            // If the target of the click is not the desired div or section
        container.has(e.target).length === 0) // ... nor a descendant-child of the container
    {
        container.hide();
    }
});

The above script will hide the div if outside of the div click event is triggered.

A: Check the window click event target (it should propagate to the window, as long as it's not captured anywhere else), and ensure that it's not any of the menu elements.  If it's not, then you're outside your menu.
Or check the position of the click, and see if it's contained within the menu area.

A: I am surprised nobody actually acknowledged focusout event:

var button = document.getElementById('button');
button.addEventListener('click', function(e){
  e.target.style.backgroundColor = 'green';
});
button.addEventListener('focusout', function(e){
  e.target.style.backgroundColor = '';
});
<!DOCTYPE html>

  <meta charset="utf-8">

  <button id="button">Click</button>

A: Solution1
Instead of using event.stopPropagation() which can have some side affects, just define a simple flag variable and add one if condition. I tested this and worked properly without any side affects of stopPropagation:
var flag = "1";
$('#menucontainer').click(function(event){
    flag = "0"; // flag 0 means click happened in the area where we should not do any action
});

$('html').click(function() {
    if(flag != "0"){
        // Hide the menus if visible
    }
    else {
        flag = "1";
    }
});

Solution2
With just a simple if condition:
$(document).on('click', function(event){
    var container = $("#menucontainer");
    if (!container.is(event.target) &&            // If the target of the click isn't the container...
        container.has(event.target).length === 0) // ... nor a descendant of the container
    {
        // Do whatever you want to do when click is outside the element
    }
});

A: 2020 solution using native JS API closest method.

document.addEventListener('click', ({ target }) => {
  if (!target.closest('#menupop')) {
    document.querySelector('#menupop').style.display = 'none'
  }
})
#menupop {
    width: 300px;
    height: 300px;
    background-color: red;
}

clicking outside will close this

A: This worked perfectly fine in time for me:
$('body').click(function() {
    // Hide the menus if visible.
});

A: To be honest, I didn't like any of previous the solutions.
The best way to do this, is binding the "click" event to the document, and comparing if that click is really outside the element (just like Art said in his suggestion).
However, you'll have some problems there: You'll never be able to unbind it, and you cannot have an external button to open/close that element.
That's why I wrote this small plugin (click here to link), to simplify these tasks. Could it be simpler?
Toggle the menu

    I should be toggled when the above menu is clicked,
    and hidden when user clicks outside.

A: One more solution is here:
http://jsfiddle.net/zR76D/
Usage:

Open / Close Menu

I am a menu, whoa is me.

Plugin:
(function($) {
    var clickOutsideElements = [];
    var clickListener = false;

    $.fn.clickOutside = function(options, ignoreFirstClick) {
        var that = this;
        if (ignoreFirstClick == null) ignoreFirstClick = true;

        if (options != "disable") {
            for (var i in clickOutsideElements) {
                if (clickOutsideElements[i].element[0] == $(this)[0]) return this;
            }

            clickOutsideElements.push({ element : this, clickDetected : ignoreFirstClick, fnc : (typeof(options) != "function") ? function() {} : options });

            $(this).on("click.clickOutside", function(event) {
                for (var i in clickOutsideElements) {
                    if (clickOutsideElements[i].element[0] == $(this)[0]) {
                        clickOutsideElements[i].clickDetected = true;
                    }
                }
            });

            if (!clickListener) {
                if (options != null && typeof(options) == "function") {
                    $('html').click(function() {
                        for (var i in clickOutsideElements) {
                            if (!clickOutsideElements[i].clickDetected) {
                                clickOutsideElements[i].fnc.call(that);
                            }
                            if (clickOutsideElements[i] != null) clickOutsideElements[i].clickDetected = false;
                        }
                    });
                    clickListener = true;
                }
            }
        }
        else {
            $(this).off("click.clickoutside");
            for (var i = 0; i < clickOutsideElements.length; ++i) {
                if (clickOutsideElements[i].element[0] == $(this)[0]) {
                    clickOutsideElements.splice(i, 1);
                }
            }
        }

        return this;
    }
})(jQuery);

A: The broadest way to do this is to select everything on the web page except the element where you don't want clicks detected and bind the click event those when the menu is opened.
Then when the menu is closed remove the binding.
Use .stopPropagation to prevent the event from affecting any part of the menuscontainer.
$("*").not($("#menuscontainer")).bind("click.OutsideMenus", function ()
{
    // hide the menus

    //then remove all of the handlers
    $("*").unbind(".OutsideMenus");
});

$("#menuscontainer").bind("click.OutsideMenus", function (event)
{
    event.stopPropagation();
});

A: For touch devices like iPad and iPhone we can use this code:
$(document).on('touchstart', function (event) {
    var container = $("YOUR CONTAINER SELECTOR");

    if (!container.is(e.target) &&            // If the target of the click isn't the container...
        container.has(e.target).length === 0) // ... nor a descendant of the container
    {
        container.hide();
    }
});

A: This might be a better fix for some people.
$(".menu_link").click(function(){
    // show menu code
});

$(".menu_link").mouseleave(function(){
    //hide menu code, you may add a timer for 3 seconds before code to be run
});

I know mouseleave does not only mean a click outside, it also means leaving that element's area.
Once the menu itself is inside the menu_link element then the menu itself should not be a problem to click on or move on.

A: I believe the best way of doing it is something like this.
$(document).on("click", function(event) {
  clickedtarget = $(event.target).closest('#menuscontainer');
  $("#menuscontainer").not(clickedtarget).hide();
});

This type of solution could easily be made to work for multiple menus and also menus that are dynamically added through javascript. Basically it just allows you to click anywhere in your document, and checks which element you clicked in, and selects it's closest "#menuscontainer". Then it hides all menuscontainers but excludes the one you clicked in.
Not sure about exactly how your menus are built, but feel free to copy my code in the JSFiddle. It's a very simple but thoroughly functional menu/modal system. All you need to do is build the html-menus and the code will do the work for you.
https://jsfiddle.net/zs6anrn7/

A: $(document).on("click",function (event)
 {
     console.log(event);
   if ($(event.target).closest('.element').length == 0)
     {
    //your code here
      if ($(".element").hasClass("active"))
      {
        $(".element").removeClass("active");
      }
     }
 });

Try this coding for getting the solution.

A: This works for me
$("body").mouseup(function(e) {
    var subject = $(".main-menu");
    if(e.target.id != subject.attr('id') && !subject.has(e.target).length) {
        $('.sub-menu').hide();
    }
});

A: Still looking for that perfect solution for detecting clicking outside? Look no further! Introducing Clickout-Event, a package that provides universal support for clickout and other similar events, and it works in all scenarios: plain HTML onclickout attributes, .addEventListener('clickout') of vanilla JavaScript, .on('clickout') of jQuery, v-on:clickout directives of Vue.js, you name it. As long as a front-end framework internally uses addEventListener to handle events, Clickout-Event works for it. Just add the script tag anywhere in your page, and it simply works like magic.
HTML attribute

...

Vanilla JavaScript
document.getElementById('myId').addEventListener('clickout', myListener);

jQuery
$('#myId').on('clickout', myListener);

Vue.js

...

Angular

...

A: This is the simplest answer I have found to this question:
window.addEventListener('click', close_window = function () {
  if(event.target !== windowEl){
    windowEl.style.display = "none";
    window.removeEventListener('click', close_window, false);
  }
});

And you will see I named the function "close_window" so that I could remove the event listener when the window closes.

A: A way to write in pure JavaScript
let menu = document.getElementById("menu");

document.addEventListener("click", function(){
    // Hide the menus
    menu.style.display = "none";
}, false);

document.getElementById("menuscontainer").addEventListener("click", function(e){
    // Show the menus
    menu.style.display = "block";
    e.stopPropagation();
}, false);

A:
Note: Using stopPropagation is something that should be avoided as it breaks normal event flow in the DOM. See this CSS Tricks article for more information. Consider using this method instead.

Attach a click event to the document body which closes the window. Attach a separate click event to the container which stops propagation to the document body.
$(window).click(function() {
  //Hide the menus if visible
});

$('#menucontainer').click(function(event){
  event.stopPropagation();
});

A: I've had success with something like this:
var $menuscontainer = ...;

$('#trigger').click(function() {
  $menuscontainer.show();

  $('body').click(function(event) {
    var $target = $(event.target);

    if ($target.parents('#menuscontainer').length == 0) {
      $menuscontainer.hide();
    }
  });
});

The logic is: when #menuscontainer is shown, bind a click handler to the body that hides #menuscontainer only if the target (of the click) isn't a child of it.

A: The other solutions here didn't work for me so I had to use:
if(!$(event.target).is('#foo'))
{
    // hide menu
}

Edit: Plain Javascript variant (2021-03-31)
I used this method to handle closing a drop down menu when clicking outside of it.
First, I created a custom class name for all the elements of the component. This class name will be added to all elements that make up the menu widget.
const className = `dropdown-${Date.now()}-${Math.random() * 100}`;

I create a function to check for clicks and the class name of the clicked element. If clicked element does not contain the custom class name I generated above, it should set the show flag to false and the menu will close.
const onClickOutside = (e) => {
  if (!e.target.className.includes(className)) {
    show = false;
  }
};

Then I attached the click handler to the window object.
// add when widget loads
window.addEventListener("click", onClickOutside);

... and finally some housekeeping
// remove listener when destroying the widget
window.removeEventListener("click", onClickOutside);

A: The event has a property called event.path of the element which is a "static ordered list of all its ancestors in tree order". To check if an event originated from a specific DOM element or one of its children, just check the path for that specific DOM element. It can also be used to check multiple elements by logically ORing the element check in the some function.

$("body").click(function() {
  target = document.getElementById("main");
  flag = event.path.some(function(el, i, arr) {
    return (el == target)
  })
  if (flag) {
    console.log("Inside")
  } else {
    console.log("Outside")
  }
});
#main {
  display: inline-block;
  background:yellow;
}

Test-Main

Test-Main

Test-Main

Test-Main

Test-Main

  Outside Main

So for your case It should be
$("body").click(function() {
  target = $("#menuscontainer")[0];
  flag = event.path.some(function(el, i, arr) {
    return (el == target)
  });
  if (!flag) {
    // Hide the menus
  }
});

A: As a variant:
var $menu = $('#menucontainer');
$(document).on('click', function (e) {

    // If element is opened and click target is outside it, hide it
    if ($menu.is(':visible') && !$menu.is(e.target) && !$menu.has(e.target).length) {
        $menu.hide();
    }
});

It has no problem with stopping event propagation and better supports multiple menus on the same page where clicking on a second menu while a first is open will leave the first open in the stopPropagation solution.

A: Use focusout for accessibility
There is one answer here that says (quite correctly) that focusing on click events is an accessibility problem since we want to cater for keyboard users. The focusout event is the correct thing to use here, but it can be done much more simply than in the other answer (and in pure JavaScript too):
A simpler way of doing it:
The 'problem' with using focusout is that if an element inside your dialog/modal/menu loses focus, to something also 'inside', the event will still get fired. We can check that this isn't the case by looking at event.relatedTarget (which tells us what element will have gained focus).
dialog = document.getElementById("dialogElement")

dialog.addEventListener("focusout", function (event) {
    if (
        // We are still inside the dialog so don't close
        dialog.contains(event.relatedTarget) ||
        // We have switched to another tab so probably don't want to close
        !document.hasFocus()
    ) {
        return;
    }
    dialog.close();  // Or whatever logic you want to use to close
});

There is one slight gotcha to the above, which is that relatedTarget may be null. This is fine if the user is clicking outside the dialog, but will be a problem if unless the user clicks inside the dialog and the dialog happens to not be focusable. To fix this you have to make sure to set tabIndex=0 so your dialog is focusable.

A: You can listen for a click event on document and then make sure #menucontainer is not an ancestor or the target of the clicked element by using  .closest().
If it is not, then the clicked element is outside of the #menucontainer and you can safely hide it.
$(document).click(function(event) {
  var $target = $(event.target);
  if(!$target.closest('#menucontainer').length &&
  $('#menucontainer').is(":visible")) {
    $('#menucontainer').hide();
  }
});

Edit – 2017-06-23
You can also clean up after the event listener if you plan to dismiss the menu and want to stop listening for events. This function will clean up only the newly created listener, preserving any other click listeners on document. With ES2015 syntax:
export function hideOnClickOutside(selector) {
  const outsideClickListener = (event) => {
    const $target = $(event.target);
    if (!$target.closest(selector).length && $(selector).is(':visible')) {
        $(selector).hide();
        removeClickListener();
    }
  }

  const removeClickListener = () => {
    document.removeEventListener('click', outsideClickListener);
  }

  document.addEventListener('click', outsideClickListener);
}

Edit – 2018-03-11
For those who don't want to use jQuery. Here's the above code in plain vanillaJS (ECMAScript6).
function hideOnClickOutside(element) {
    const outsideClickListener = event => {
        if (!element.contains(event.target) && isVisible(element)) { // or use: event.target.closest(selector) === null
          element.style.display = 'none';
          removeClickListener();
        }
    }

    const removeClickListener = () => {
        document.removeEventListener('click', outsideClickListener);
    }

    document.addEventListener('click', outsideClickListener);
}

const isVisible = elem => !!elem && !!( elem.offsetWidth || elem.offsetHeight || elem.getClientRects().length ); // source (2018-03-11): https://github.com/jquery/jquery/blob/master/src/css/hiddenVisibleSelectors.js

NOTE:
This is based on Alex comment to just use !element.contains(event.target) instead of the jQuery part.
But element.closest() is now also available in all major browsers (the W3C version differs a bit from the jQuery one).
Polyfills can be found here: Element.closest()
Edit – 2020-05-21
In the case where you want the user to be able to click-and-drag inside the element, then release the mouse outside the element, without closing the element:
      ...
      let lastMouseDownX = 0;
      let lastMouseDownY = 0;
      let lastMouseDownWasOutside = false;

      const mouseDownListener = (event: MouseEvent) => {
        lastMouseDownX = event.offsetX;
        lastMouseDownY = event.offsetY;
        lastMouseDownWasOutside = !$(event.target).closest(element).length;
      }
      document.addEventListener('mousedown', mouseDownListener);

And in outsideClickListener:
const outsideClickListener = event => {
        const deltaX = event.offsetX - lastMouseDownX;
        const deltaY = event.offsetY - lastMouseDownY;
        const distSq = (deltaX * deltaX) + (deltaY * deltaY);
        const isDrag = distSq > 3;
        const isDragException = isDrag && !lastMouseDownWasOutside;

        if (!element.contains(event.target) && isVisible(element) && !isDragException) { // or use: event.target.closest(selector) === null
          element.style.display = 'none';
          removeClickListener();
          document.removeEventListener('mousedown', mouseDownListener); // Or add this line to removeClickListener()
        }
    }

A: I found this method in some jQuery calendar plugin.
function ClickOutsideCheck(e)
{
  var el = e.target;
  var popup = $('.popup:visible')[0];
  if (popup==undefined)
    return true;

  while (true){
    if (el == popup ) {
      return true;
    } else if (el == document) {
      $(".popup").hide();
      return false;
    } else {
      el = $(el).parent()[0];
    }
  }
};

$(document).bind('mousedown.popup', ClickOutsideCheck);

A: I have an application that works similarly to Eran's example, except I attach the click event to the body when I open the menu... Kinda like this:
$('#menucontainer').click(function(event) {
  $('html').one('click',function() {
    // Hide the menus
  });

  event.stopPropagation();
});

More information on jQuery's one() function

A: Here is the vanilla JavaScript solution for future viewers.
Upon clicking any element within the document, if the clicked element's id is toggled, or the hidden element is not hidden and the hidden element does not contain the clicked element, toggle the element.
(function () {
    "use strict";
    var hidden = document.getElementById('hidden');
    document.addEventListener('click', function (e) {
        if (e.target.id == 'toggle' || (hidden.style.display != 'none' && !hidden.contains(e.target))) hidden.style.display = hidden.style.display == 'none' ? 'block' : 'none';
    }, false);
})();

(function () {
    "use strict";
    var hidden = document.getElementById('hidden');
    document.addEventListener('click', function (e) {
        if (e.target.id == 'toggle' || (hidden.style.display != 'none' && !hidden.contains(e.target))) hidden.style.display = hidden.style.display == 'none' ? 'block' : 'none';
    }, false);
})();
Toggle Hidden Div

This content is normally hidden. click anywhere other than this content to make me disappear

If you are going to have multiple toggles on the same page you can use something like this:

*

*Add the class name hidden to the collapsible item.

*Upon document click, close all hidden elements which do not contain the clicked element and are not hidden

*If the clicked element is a toggle, toggle the specified element.

(function () {
    "use strict";
    var hiddenItems = document.getElementsByClassName('hidden'), hidden;
    document.addEventListener('click', function (e) {
        for (var i = 0; hidden = hiddenItems[i]; i++) {
            if (!hidden.contains(e.target) && hidden.style.display != 'none')
                hidden.style.display = 'none';
        }
        if (e.target.getAttribute('data-toggle')) {
            var toggle = document.querySelector(e.target.getAttribute('data-toggle'));
            toggle.style.display = toggle.style.display == 'none' ? 'block' : 'none';
        }
    }, false);
})();
Toggle Hidden Div

This content is normally hidden

Toggle Hidden Div

This content is normally hidden

Toggle Hidden Div

This content is normally hidden

A: It's 2020 and you can use event.composedPath()
From: Event.composedPath()

The composedPath() method of the Event interface returns the event's path, which is an array of the objects on which listeners will be invoked.

const target = document.querySelector('#myTarget')

document.addEventListener('click', (event) => {
  const withinBoundaries = event.composedPath().includes(target)

  if (withinBoundaries) {
    target.innerText = 'Click happened inside element'
  } else {
    target.innerText = 'Click happened **OUTSIDE** element'
  }
})
/* Just to make it good looking. You don't need this */
#myTarget {
  margin: 50px auto;
  width: 500px;
  height: 500px;
  background: gray;
  border: 10px solid black;
}

  Click me (or not!)

A: Here is my code:
// Listen to every click
$('html').click(function(event) {
    if ( $('#mypopupmenu').is(':visible') ) {
        if (event.target.id != 'click_this_to_show_mypopupmenu') {
            $('#mypopupmenu').hide();
        }
    }
});

// Listen to selector's clicks
$('#click_this_to_show_mypopupmenu').click(function() {

  // If the menu is visible, and you clicked the selector again we need to hide
  if ( $('#mypopupmenu').is(':visible') {
      $('#mypopupmenu').hide();
      return true;
  }

  // Else we need to show the popup menu
  $('#mypopupmenu').show();
});

A: jQuery().ready(function(){
    $('#nav').click(function (event) {
        $(this).addClass('activ');
        event.stopPropagation();
    });

    $('html').click(function () {
        if( $('#nav').hasClass('activ') ){
            $('#nav').removeClass('activ');
        }
    });
});

A: Just a warning that using this:
$('html').click(function() {
  // Hide the menus if visible
});

$('#menucontainer').click(function(event){
  event.stopPropagation();
});

It prevents the Ruby on Rails UJS driver from working properly. For example, link_to 'click', '/url', :method => :delete will not work.
This might be a workaround:
$('html').click(function() {
  // Hide the menus if visible
});

$('#menucontainer').click(function(event){
  if (!$(event.target).data('method')) {
    event.stopPropagation();
  }
});

A: This is a more general solution that allows multiple elements to be watched, and dynamically adding and removing elements from the queue.
It holds a global queue (autoCloseQueue) - an object container for elements that should be closed on outside clicks.
Each queue object key should be the DOM Element id, and the value should be an object with 2 callback functions:
 {onPress: someCallbackFunction, onOutsidePress: anotherCallbackFunction}

Put this in your document ready callback:
window.autoCloseQueue = {}

$(document).click(function(event) {
    for (id in autoCloseQueue){
        var element = autoCloseQueue[id];
        if ( ($(e.target).parents('#' + id).length) > 0) { // This is a click on the element (or its child element)
            console.log('This is a click on an element (or its child element) with  id: ' + id);
            if (typeof element.onPress == 'function') element.onPress(event, id);
        } else { //This is a click outside the element
            console.log('This is a click outside the element with id: ' + id);
            if (typeof element.onOutsidePress == 'function') element.onOutsidePress(event, id); //call the outside callback
            delete autoCloseQueue[id]; //remove the element from the queue
        }
    }
});

Then, when the DOM element with id  'menuscontainer' is created, just add this object to the queue:
window.autoCloseQueue['menuscontainer'] = {onOutsidePress: clickOutsideThisElement}

A: Simple plugin:
$.fn.clickOff = function(callback, selfDestroy) {
    var clicked = false;
    var parent = this;
    var destroy = selfDestroy || true;

    parent.click(function() {
        clicked = true;
    });

    $(document).click(function(event) {
        if (!clicked && parent.is(':visible')) {
            if(callback) callback.call(parent, event)
        }
        if (destroy) {
            //parent.clickOff = function() {};
            //parent.off("click");
            //$(document).off("click");
            parent.off("clickOff");
        }
        clicked = false;
    });
};

Use:
$("#myDiv").clickOff(function() {
   alert('clickOff');
});

A: $('#propertyType').on("click",function(e){
          self.propertyTypeDialog = !self.propertyTypeDialog;
          b = true;
          e.stopPropagation();
          console.log("input clicked");
      });

      $(document).on('click','body:not(#propertyType)',function (e) {
          e.stopPropagation();
          if(b == true)  {
              if ($(e.target).closest("#configuration").length == 0) {
                  b = false;
                  self.propertyTypeDialog = false;
                  console.log("outside clicked");
              }
          }
        // console.log($(e.target).closest("#configuration").length);
      });

A:

const button = document.querySelector('button')
const box = document.querySelector('.box');

const toggle = event => {
  event.stopPropagation();

  if (!event.target.closest('.box')) {
    console.log('Click outside');

    box.classList.toggle('active');

    box.classList.contains('active')
      ? document.addEventListener('click', toggle)
      : document.removeEventListener('click', toggle);
  } else {
    console.log('Click inside');
  }
}

button.addEventListener('click', toggle);
.box {
  position: absolute;
  display: none;
  margin-top: 8px;
  padding: 20px;
  background: lightgray;
}

.box.active {
  display: block;
}
<button>Toggle box</button>

  <form action="">
    <input type="text">
    <button type="button">Search</button>
  </form>

A: This will toggle the Nav menu when you click on/off the element.

$(document).on('click', function(e) {
  var elem = $(e.target).closest('#menu'),
    box = $(e.target).closest('#nav');
  if (elem.length) {
    e.preventDefault();
    $('#nav').toggle();
  } else if (!box.length) {
    $('#nav').hide();
  }
});

Page1

Page2

Page3

Page4

A: Outside click plugin!
Usage:
$('.target-element').outsideClick(function(event){
    //code that fires when user clicks outside the element
    //event = the click event
    //$(this) = the '.target-element' that is firing this function
}, '.excluded-element')

The code for it:
(function($) {

//when the user hits the escape key, it will trigger all outsideClick functions
$(document).on("keyup", function (e) {
    if (e.which == 27) $('body').click(); //escape key
});

//The actual plugin
$.fn.outsideClick = function(callback, exclusions) {
    var subject = this;

    //test if exclusions have been set
    var hasExclusions = typeof exclusions !== 'undefined';

    //switches click event with touch event if on a touch device
    var ClickOrTouchEvent = "ontouchend" in document ? "touchend" : "click";

    $('body').on(ClickOrTouchEvent, function(event) {
        //click target does not contain subject as a parent
        var clickedOutside = !$(event.target).closest(subject).length;

        //click target was on one of the excluded elements
        var clickedExclusion = $(event.target).closest(exclusions).length;

        var testSuccessful;

        if (hasExclusions) {
            testSuccessful = clickedOutside && !clickedExclusion;
        } else {
            testSuccessful = clickedOutside;
        }

        if(testSuccessful) {
            callback.call(subject, event);
        }
    });

    return this;
};

}(jQuery));

Adapted from this answer https://stackoverflow.com/a/3028037/1611058

A: Subscribe capturing phase of click to handle click on elements which call preventDefault.
Retrigger it on document element using the other name click-anywhere.
document.addEventListener('click', function (event) {
  event = $.event.fix(event);
  event.type = 'click-anywhere';
  $document.trigger(event);
}, true);

Then where you need click outside functionality subscribe on click-anywhere event on document and check if the click was outside of the element you are interested in:
$(document).on('click-anywhere', function (event) {
  if (!$(event.target).closest('#smth').length) {
    // Do anything you need here
  }
});

Some notes:

*

*You have to use document as it would be a perfomance fault to trigger event on all elements outside of which the click occured.

*This functionality can be wrapped into special plugin, which calls some callback on outside click.

*You can't subscribe capturing phase using jQuery itself.

*You don't need document load to subscribe as subscription is on document, even not on its body, so it exists always independently ащкь script placement and load status.

A: To hide fileTreeClass if clicked outside of it:
jQuery(document).mouseup(function (e) {
    var container = $(".fileTreeClass");
    if (!container.is(e.target) && // If the target of the click isn't the container...
         container.has(e.target).length === 0) // ... nor a descendant of the container
    {
        container.hide();
    }
});

A: if you just want to display a window when you click on a button and undisp this window when you click outside.( or on the button again ) this bellow work good
document.body.onclick = function() { undisp_menu(); };
var menu_on = 0;

function menu_trigger(event){

    if (menu_on == 0)
    {
        // otherwise u will call the undisp on body when
        // click on the button
        event.stopPropagation();

        disp_menu();
    }

    else{
        undisp_menu();
    }

}

function disp_menu(){

    menu_on = 1;
    var e = document.getElementsByClassName("menu")[0];
    e.className = "menu on";

}

function undisp_menu(){

    menu_on = 0;
    var e = document.getElementsByClassName("menu")[0];
    e.className = "menu";

}

don't forget this for the button

and the css:
.menu{
    display: none;
}

.on {
    display: inline-block;
}

A: I've read all on 2021, but if not wrong, nobody suggested something easy like this, to unbind and remove event. Using two of the previous answers and a more small tricks, so I put all in one (it could also be added as a parameter to the function to pass selectors, for more popups).
Maybe it is useful for someone to know that the joke. It could also be done this way:

my menu is nice, but it disappears if I click outside it

A: You don't need (much) JavaScript, just the :focus-within selector:

*

*Use .sidebar:focus-within to display your sidebar.

*Set tabindex=-1 on your sidebar and body elements to make them focussable.

*Set the sidebar visibility with sidebarEl.focus() and document.body.focus().

const menuButton = document.querySelector('.menu-button');
const sidebar = document.querySelector('.sidebar');

menuButton.onmousedown = ev => {
  ev.preventDefault();
  (sidebar.contains(document.activeElement) ?
    document.body : sidebar).focus();
};
* { box-sizing: border-box; }

.sidebar {
  position: fixed;
  width: 15em;
  left: -15em;
  top: 0;
  bottom: 0;
  transition: left 0.3s ease-in-out;
  background-color: #eef;
  padding: 3em 1em;
}

.sidebar:focus-within {
  left: 0;
}

.sidebar:focus {
  outline: 0;
}

.menu-button {
  position: fixed;
  top: 0;
  left: 0;
  padding: 1em;
  background-color: #eef;
  border: 0;
}

body {
  max-width: 30em;
  margin: 3em;
}

    Sidebar content
    <input type="text"/>

  <button class="menu-button">☰</button>
  Body content goes here, Lorem ipsum sit amet, etc

A: For those who want a short solution to integrate into their JS code - a small library without JQuery:
Usage:
// demo code
var htmlElem = document.getElementById('my-element')
function doSomething(){ console.log('outside click') }

// use the lib
var removeListener = new elemOutsideClickListener(htmlElem, doSomething);

// deregister on your wished event
$scope.$on('$destroy', removeListener);

Here is the lib:

function elemOutsideClickListener (element, outsideClickFunc, insideClickFunc) {
   function onClickOutside (e) {
      var targetEl = e.target; // clicked element
      do {
         // click inside
         if (targetEl === element) {
            if (insideClickFunc) insideClickFunc();
            return;

         // Go up the DOM
         } else {
            targetEl = targetEl.parentNode;
         }
      } while (targetEl);

      // click outside
      if (!targetEl && outsideClickFunc) outsideClickFunc();
   }

   window.addEventListener('click', onClickOutside);

   return function () {
      window.removeEventListener('click', onClickOutside);
   };
}

I took the code from here and put it in a function:
https://www.w3docs.com/snippets/javascript/how-to-detect-a-click-outside-an-element.html

A:

function hidefeedback(){
    $j(".feedbackhide").hide();
}

function showfeedback(){
    $j(".feedbackhide").show();
    $j(".feedbackCont").attr("tabindex",1).focus();
}

This is the simplest solution I came up with.

A: Try this code:
if ($(event.target).parents().index($('#searchFormEdit')) == -1 &&
    $(event.target).parents().index($('.DynarchCalendar-topCont')) == -1 &&
    (_x < os.left || _x > (os.left + 570) || _y < os.top || _y > (os.top + 155)) &&
    isShowEditForm) {

    setVisibleEditForm(false);
}

A: You can set a tabindex to the DOM element. This will trigger a blur event when the user click outside the DOM element.
Demo

    Focus me

document.querySelector("div").onblur = function(){
   console.log('clicked outside')
}
document.querySelector("div").onfocus = function(){
   console.log('clicked inside')
}

A: Standard HTML:
Surround the menus by a  and fetch focus state changes.
http://jsfiddle.net/bK3gL/
Plus: you can unfold the menu by Tab.

A: Using not():
$("#id").not().click(function() {
    alert('Clicked other that #id');
});

A: $("body > div:not(#dvid)").click(function (e) {
    //your code
});

A: $("html").click(function(){
    if($('#info').css("opacity")>0.9) {
        $('#info').fadeOut('fast');
    }
});

A: This is a classic case of where a tweak to the HTML would be a better solution. Why not set the click on the elements which don't contain the menu item? Then you don't need to add the propagation.
$('.header, .footer, .main-content').click(function() {
//Hide the menus if visible
});

A: The easiest way: mouseleave(function())
More info: https://www.w3schools.com/jquery/jquery_events.asp

A:     $('#menucontainer').click(function(e){
        e.stopPropagation();
     });

    $(document).on('click',  function(e){
        // code
    });

A: As a wrapper to this great answer from Art, and to use the syntax originally requested by OP, here's a jQuery extension that can record wether a click occured outside of a set element.
$.fn.clickOutsideThisElement = function (callback) {
    return this.each(function () {
        var self = this;
        $(document).click(function (e) {
            if (!$(e.target).closest(self).length) {
                callback.call(self, e)
            }
        })
    });
};

Then you can call like this:
$("#menuscontainer").clickOutsideThisElement(function() {
    // handle menu toggle
});

Here's a demo in fiddle

A:

$('html').click(function() {
//Hide the menus if visible
});

$('#menucontainer').click(function(event){
    event.stopPropagation();
});

 <button id='#menucontainer'>Ok</button>

A: Have a try of this:
$('html').click(function(e) {
  if($(e.target).parents('#menuscontainer').length == 0) {
    $('#menuscontainer').hide();
  }
});

https://jsfiddle.net/4cj4jxy0/
But note that this cannot work if the click event cannot reach the html tag. (Maybe other elements have stopPropagation()).

A: $(document).on('click.menu.hide', function(e){
  if ( !$(e.target).closest('#my_menu').length ) {
    $('#my_menu').find('ul').toggleClass('active', false);
  }
});

$(document).on('click.menu.show', '#my_menu li', function(e){
  $(this).find('ul').toggleClass('active');
});

div {
  float: left;
}

ul {
  padding: 0;
  position: relative;
}
ul li {
  padding: 5px 25px 5px 10px;
  border: 1px solid silver;
  cursor: pointer;
  list-style: none;
  margin-top: -1px;
  white-space: nowrap;
}
ul li ul:before {
  margin-right: -20px;
  position: absolute;
  top: -17px;
  right: 0;
  content: "\25BC";
}
ul li ul li {
  visibility: hidden;
  height: 0;
  padding-top: 0;
  padding-bottom: 0;
  border-width: 0 0 1px 0;
}
ul li ul li:last-child {
  border: none;
}
ul li ul.active:before {
  content: "\25B2";
}
ul li ul.active li {
  display: list-item;
  visibility: visible;
  height: inherit;
  padding: 5px 25px 5px 10px;
}

Menu 1

subMenu 1

subMenu 2

subMenu 3

subMenu 4

Menu 2

subMenu 1

subMenu 2

subMenu 3

subMenu 4

Menu 3

Menu 4

Menu 5

Menu 6

Here is jsbin version http://jsbin.com/xopacadeni/edit?html,css,js,output

A: First you have to track wether the mouse is inside or outside your element1, using the mouseenter and mouseleave events.
Then you can create an element2 which covers the whole screen to detect any clicks, and react accordingly depending on wether you are inside or outside element1.
I strongly recommend to handle both initialization and cleanup, and that the element2 is made as temporary as possible, for obvious reasons.
In the example below, the overlay is an element positionned somewhere, which can be selected by clicking inside, and unselected by clicking outside.
The _init and _release methods are called as part of an automatic initialisation/cleanup process.
The class inherits from a ClickOverlay which has an inner and outerElement, don't worry about it. I used outerElement.parentNode.appendChild to avoid conflicts.
import ClickOverlay from './ClickOverlay.js'

/* CSS */
// .unselect-helper {
//  position: fixed; left: -100vw; top: -100vh;
//  width: 200vw; height: 200vh;
// }
// .selected {outline: 1px solid black}

export default class ResizeOverlay extends ClickOverlay {
    _init(_opts) {
        this.enterListener = () => this.onEnter()
        this.innerElement.addEventListener('mouseenter', this.enterListener)
        this.leaveListener = () => this.onLeave()
        this.innerElement.addEventListener('mouseleave', this.leaveListener)
        this.selectListener = () => {
            if (this.unselectHelper)
                return
            this.unselectHelper = document.createElement('div')
            this.unselectHelper.classList.add('unselect-helper')
            this.unselectListener = () => {
                if (this.mouseInside)
                    return
                this.clearUnselectHelper()
                this.onUnselect()
            }
            this.unselectHelper.addEventListener('pointerdown'
                , this.unselectListener)
            this.outerElement.parentNode.appendChild(this.unselectHelper)
            this.onSelect()
        }
        this.innerElement.addEventListener('pointerup', this.selectListener)
    }

    _release() {
        this.innerElement.removeEventListener('mouseenter', this.enterListener)
        this.innerElement.removeEventListener('mouseleave', this.leaveListener)
        this.innerElement.removeEventListener('pointerup', this.selectListener)
        this.clearUnselectHelper()
    }

    clearUnselectHelper() {
        if (!this.unselectHelper)
            return
        this.unselectHelper.removeEventListener('pointerdown'
            , this.unselectListener)
        this.unselectHelper.remove()
        delete this.unselectListener
        delete this.unselectHelper
    }

    onEnter() {
        this.mouseInside = true
    }

    onLeave() {
        delete this.mouseInside
    }

    onSelect() {
        this.innerElement.classList.add('selected')
    }

    onUnselect() {
        this.innerElement.classList.remove('selected')
    }
}

A: This works fine for me. I am not an expert.
$(document).click(function(event) {
  var $target = $(event.target);
  if(!$target.closest('#hamburger, a').length &&
  $('#hamburger, a').is(":visible")) {
    $('nav').slideToggle();
  }
});

A: Here is solution within a container or whole document. If click target is out of your element (with class 'yourClass'), element is hidden.
$('yourContainer').on('click', function(e) {
  if (!$(e.target).hasClass('yourClass')) {
    $('.yourClass').hide();
  }
});


text:
Q: How do I post image and text to Twitter via Twitter native app? How do I post image and text to Twitter via Twitter native app ?
Is there any Twitter api to tweet via native Twitter app in IOS programmatically ?
or , How can I post image using Social or Twitter framework via Twitter native app?
Thanks

A: Please Try this answer. I think this will help u
  - (void)postToTwitter
 {
SLComposeViewController *tweetSheet=[SLComposeViewController composeViewControllerForServiceType:SLServiceTypeTwitter];
//     if([SLComposeViewController isAvailableForServiceType:SLServiceTypeTwitter])
//     {
SLComposeViewControllerCompletionHandler __block    completionHandler=^(SLComposeViewControllerResult result){

    [tweetSheet dismissViewControllerAnimated:YES completion:nil];

    switch(result){
        case SLComposeViewControllerResultCancelled:
        default:
        {
            NSLog(@"Cancel");
        }
            break;
        case SLComposeViewControllerResultDone:
        {
            NSLog(@"Post");
        }
            break;
    }
};

[tweetSheet setInitialText:@"your text"];
[tweetSheet addImage:[UIImage imageNamed:@"imageToSend"]];
[tweetSheet setCompletionHandler:completionHandler];
[self presentViewController:tweetSheet animated:YES completion:nil];
//}

}

A: Hi for sharing information via iOS app it is possible to use native share screen.
Using this code you going to share image via different social media.
UIImage *picture = [UIImage imageNamed:@"picture"];
UIActivityViewController *activityViewController = [[UIActivityViewController alloc] initWithActivityItems:@[picture] applicationActivities:nil];


text:
Q: Static variable link error in MSVC even though it is created in the cpp file I am working on a cross-platform (Linux & Windows) library. One of my class has a static member defined in the header. And I created it in a CPP file like
namespace raisim {
std::function<void()> RaiSimMsg::fatalCallback_ = []() { exit(1); };
}

The header file
#ifndef RAISIM_MESSAGE_LOGGER_HPP
#define RAISIM_MESSAGE_LOGGER_HPP

#include <chrono>
...

namespace raisim {

class RaiSimMsg {
 public:
  ...
  void stream(const char *file, const int line, std::stringstream &msg, int severity) {
    if (severity == RSEVERITY_FATAL)
      fatalCallback_();
  }

 private:
   static std::function<void()> fatalCallback_;
};

}

#endif //RAISIM_MESSAGE_LOGGER_HPP

This works perfectly with GCC and Clang in Linux. But MSVC is giving a link error. Does MSVC have its own rules for static members??
Full error log
1>anymal.obj : error LNK2001: unresolved external symbol "private: static class std::function<void __cdecl(void)> raisim::RaiSimMsg::fatalCallback_" (?fatalCallback_@RaiSimMsg@raisim@@0V?$function@$$A6AXXZ@std@@A)
1>C:\Users\ultrafrog\source\repos\raisim\build\benchmark\Debug\speed_test_anymal.exe : fatal error LNK1120: 1 unresolved externals
1>Done building project "speed_test_anymal.vcxproj" -- FAILED.

A: Jack Dingler's answer here
https://www.codeproject.com/Questions/585271/Aplusstaticplusmemberplusvariableplusexportpluserr
worked. So the issue is that the Windows linker needs to know that if it has to import or export the symbol. So we have to declare __declspec(dllexport) when we export (when we build the library) and  __declspec(dllimport) for using it. We can switch that using a compilation flag. I am not sure why they designed the linker like this but anyway it works now.