How do I detect a click outside an element?

JavascriptJqueryClick

Javascript Problem Overview


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
});

Javascript Solutions


Solution 1 - Javascript

> 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();
});

Solution 2 - Javascript

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()
		}
	}

Solution 3 - Javascript

> 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;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="#example">Example</a>
<div id="example" tabindex="-1">
  Lorem ipsum <a href="http://example.com">dolor</a> sit amet.
</div>


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;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="#example">Example</a>
<div id="example" tabindex="-1">
  Lorem ipsum <a href="http://example.com">dolor</a> sit amet.
</div>

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;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="#example">Example</a>
<div id="example" tabindex="-1">
  Lorem ipsum <a href="http://example.com">dolor</a> sit amet.
</div>


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;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="#example">Example</a>
<div id="example" tabindex="-1">
  Lorem ipsum <a href="http://example.com">dolor</a> sit amet.
</div>


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;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="menu">
  <li class="menu__item">
    <a class="menu__link" href="#menu-1">Menu 1</a>
    <ul class="submenu" id="menu-1" tabindex="-1">
      <li class="submenu__item"><a class="submenu__link" href="http://example.com/#1">Example 1</a></li>
      <li class="submenu__item"><a class="submenu__link" href="http://example.com/#2">Example 2</a></li>
      <li class="submenu__item"><a class="submenu__link" href="http://example.com/#3">Example 3</a></li>
      <li class="submenu__item"><a class="submenu__link" href="http://example.com/#4">Example 4</a></li>
    </ul>
  </li>
  <li class="menu__item">
    <a  class="menu__link" href="#menu-2">Menu 2</a>
    <ul class="submenu" id="menu-2" tabindex="-1">
      <li class="submenu__item"><a class="submenu__link" href="http://example.com/#1">Example 1</a></li>
      <li class="submenu__item"><a class="submenu__link" href="http://example.com/#2">Example 2</a></li>
      <li class="submenu__item"><a class="submenu__link" href="http://example.com/#3">Example 3</a></li>
      <li class="submenu__item"><a class="submenu__link" href="http://example.com/#4">Example 4</a></li>
    </ul>
  </li>
</ul>
lorem ipsum <a href="http://example.com/">dolor</a> 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.

Solution 4 - Javascript

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);

Solution 5 - Javascript

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

Solution 6 - Javascript

It's 2020 and you can use event.composedPath()

From: https://developer.mozilla.org/en-US/docs/Web/API/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;
}

<div id="myTarget">
  click me (or not!)
</div>

Solution 7 - Javascript

After research I have found three working solutions (I forgot the page links for reference)

First solution

<script>
    //The good thing about this solution is it doesn't stop event propagation.

    var clickFlag = 0;
    $('body').on('click', function () {
        if(clickFlag == 0) {
            console.log('hide element here');
            /* Hide element here */
        }
        else {
            clickFlag=0;
        }
    });
    $('body').on('click','#testDiv', function (event) {
        clickFlag = 1;
        console.log('showed the element');
        /* Show the element */
    });
</script>

Second solution

<script>
    $('body').on('click', function(e) {
        if($(e.target).closest('#testDiv').length == 0) {
           /* Hide dropdown here */
        }
    });
</script>

Third solution

<script>
    var specifiedElement = document.getElementById('testDiv');
    document.addEventListener('click', function(event) {
        var isClickInside = specifiedElement.contains(event.target);
        if (isClickInside) {
          console.log('You clicked inside')
        }
        else {
          console.log('You clicked outside')
        }
    });
</script>

Solution 8 - Javascript

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

Works for me just fine.

Solution 9 - Javascript

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.

Solution 10 - Javascript

This worked for me perfectly!!

$('html').click(function (e) {
    if (e.target.id == 'YOUR-DIV-ID') {
        //do something
    } else {
        //do something
    }
});

Solution 11 - Javascript

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.

You can see the following blog for more information : http://www.codecanal.com/detect-click-outside-div-using-javascript/

Solution 12 - Javascript

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:

  1. 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.

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

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

  4. 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.

  5. 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;}

Solution 13 - Javascript

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);
		}
	
	})
});

Solution 14 - Javascript

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.

Solution 15 - Javascript

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
    }
});

Solution 16 - Javascript

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>
<html>
<head>
  <meta charset="utf-8">
</head>
<body>
  <button id="button">Click</button>
</body>
</html>

Solution 17 - Javascript

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.

Solution 18 - Javascript

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;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="main">
  <ul>
    <li>Test-Main</li>
    <li>Test-Main</li>
    <li>Test-Main</li>
    <li>Test-Main</li>
    <li>Test-Main</li>
  </ul>
</div>
<div id="main2">
  Outside Main
</div>

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
  }
});

Solution 19 - Javascript

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.

Solution 20 - Javascript

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);

Solution 21 - Javascript

Use focusout for accessability

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.

Solution 22 - Javascript

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);
})();

<a href="javascript:void(0)" id="toggle">Toggle Hidden Div</a>
<div id="hidden" style="display: none;">This content is normally hidden. click anywhere other than this content to make me disappear</div>

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

  1. Add the class name hidden to the collapsible item.
  2. Upon document click, close all hidden elements which do not contain the clicked element and are not hidden
  3. 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);
})();

<a href="javascript:void(0)" data-toggle="#hidden1">Toggle Hidden Div</a>
<div class="hidden" id="hidden1" style="display: none;" data-hidden="true">This content is normally hidden</div>
<a href="javascript:void(0)" data-toggle="#hidden2">Toggle Hidden Div</a>
<div class="hidden" id="hidden2" style="display: none;" data-hidden="true">This content is normally hidden</div>
<a href="javascript:void(0)" data-toggle="#hidden3">Toggle Hidden Div</a>
<div class="hidden" id="hidden3" style="display: none;" data-hidden="true">This content is normally hidden</div>

Solution 23 - Javascript

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;}

Solution 24 - Javascript

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();
});

Solution 25 - Javascript

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");

Solution 26 - Javascript

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';
}

});

Solution 27 - Javascript

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;
})

Solution 28 - Javascript

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

<div class="main-container">
<div> Hello I am the title</div>
<div class="tobehide">I will hide when you click outside of me</div>
</div>

You can read the tutorial here

Solution 29 - Javascript

2020 solution using native JS API closest method.

document.addEventListener('click', ({ target }) => {
  if (!target.closest('.el1, .el2, #el3')) {
    alert('click outside')
  }
})

Solution 30 - Javascript

$(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.

Solution 31 - Javascript

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");
    }
});

Solution 32 - Javascript

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.

Solution 33 - Javascript

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).

Solution 34 - Javascript

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.

Solution 35 - Javascript

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...
});

Solution 36 - Javascript

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();
}

Solution 37 - Javascript

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();
  });
});

Solution 38 - Javascript

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
    }
});

Solution 39 - Javascript

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();
    });

Solution 40 - Javascript

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.

Solution 41 - Javascript

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;
}

Solution 42 - Javascript

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()

Solution 43 - Javascript

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.

Solution 44 - Javascript

One more solution is here:

http://jsfiddle.net/zR76D/

Usage:

<div onClick="$('#menu').toggle();$('#menu').clickOutside(function() { $(this).hide(); $(this).clickOutside('disable'); });">Open / Close Menu</div>
<div id="menu" style="display: none; border: 1px solid #000000; background: #660000;">I am a menu, whoa is me.</div>

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);

Solution 45 - Javascript

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;
            }
        }
    };
})();

Solution 46 - Javascript

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();
    }
});

Solution 47 - Javascript

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;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="outside-element"></div>
<div id="element">
  <div class="menu-item"><a href="#1">Menu Item 1</a></div>
  <div class="menu-item"><a href="#2">Menu Item 1</a></div>
  <div class="menu-item"><a href="#3">Menu Item 1</a></div>
  <div class="menu-item"><a href="#4">Menu Item 1</a></div>
</div>
<div id="show-trigger">Show Menu</div>

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.

Solution 48 - Javascript

$(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.

Solution 49 - Javascript

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();
	}
});

Solution 50 - Javascript

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;

}

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

Solution 51 - Javascript

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;
}

<div class="block"></div>

Solution 52 - Javascript

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.

Solution 53 - Javascript

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);

Solution 54 - Javascript

This worked perfectly fine in time for me:

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

Solution 55 - Javascript

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();
});

Solution 56 - Javascript

jQuery().ready(function(){
	$('#nav').click(function (event) {
		$(this).addClass('activ');
		event.stopPropagation();
	});
	
	$('html').click(function () {
		if( $('#nav').hasClass('activ') ){
			$('#nav').removeClass('activ');
		}
	});
});

Solution 57 - Javascript

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?

<a id='theButton' href="#">Toggle the menu</a><br/>
<div id='theMenu'>
    I should be toggled when the above menu is clicked,
    and hidden when user clicks outside.
</div>

<script>
$('#theButton').click(function(){
    $('#theMenu').slideDown();
});
$("#theMenu").dClickOutside({ ignoreList: $("#theButton") }, function(clickedObj){
    $(this).slideUp();
});
</script>

Solution 58 - Javascript

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(); 
});

Solution 59 - Javascript

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.

Solution 60 - Javascript

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/

Solution 61 - Javascript

$('#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);
      });

Solution 62 - Javascript

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>

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

Solution 63 - Javascript

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

<div onclickout="console.log('clickout detected')">...</div>

Vanilla JavaScript

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

jQuery

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

Vue.js

<div v-on:clickout="open=false">...</div>

Angular

<div (clickout)="close()">...</div>

Solution 64 - Javascript

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}

Solution 65 - Javascript

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();
    		}
    	});

Solution 66 - Javascript

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');
});

Solution 67 - Javascript

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();
  }
});

Solution 68 - Javascript

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();
 }
});



<li id="menu"><a></a></li>
<ul id="nav" >  //Nav will toggle when you Click on Menu(it can be an icon in this example)
        <li class="page"><a>Page1</a></li>
        <li class="page"><a>Pag2</a></li>
        <li class="page"><a>Page3</a></li>            
        <li class="page"><a>Page4</a></li>
</ul>

Solution 69 - Javascript

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

Solution 70 - Javascript

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

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

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>
 <button id='#menucontainer'>Ok</button> 
</html>

Solution 71 - Javascript

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()).

Solution 72 - Javascript

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.

Solution 73 - Javascript

$(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;
}

<script src="https://code.jquery.com/jquery-2.1.4.js"></script>
<div>
  <ul id="my_menu">
    <li>Menu 1
      <ul>
        <li>subMenu 1</li>
        <li>subMenu 2</li>
        <li>subMenu 3</li>
        <li>subMenu 4</li>
      </ul>
    </li>
    <li>Menu 2
      <ul>
        <li>subMenu 1</li>
        <li>subMenu 2</li>
        <li>subMenu 3</li>
        <li>subMenu 4</li>
      </ul>
    </li>
    <li>Menu 3</li>
    <li>Menu 4</li>
    <li>Menu 5</li>
    <li>Menu 6</li>
  </ul>
</div>

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

Solution 74 - Javascript

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

<div class="button" onclick="menu_trigger(event)">

<div class="menu">

and the css:

.menu{
    display: none;
}

.on {
    display: inline-block;
}

Solution 75 - Javascript

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();
  }
});

Solution 76 - Javascript

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 above answers and a more little trick so put all in one (could also be added param to the function to pass selectors, for more popups). May it is useful for someone to know that the joke could be done also this way:

<div id="container" style="display:none"><h1>my menu is nice but disappear if i click outside it</h1></div>

<script>
 function printPopup(){
  $("#container").css({ "display":"block" });
  var remListener = $(document).mouseup(function (e) {
   if ($(e.target).closest("#container").length === 0 && (e.target != $('html').get(0))) 
   {
    //alert('closest call');
    $("#container").css({ "display":"none" });
    remListener.unbind('mouseup'); // isn't it?
   } 
  });
 }

 printPopup();

</script>

cheers

Solution 77 - Javascript

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;
}

<body tabindex='-1'>
  <nav class='sidebar' tabindex='-1'>
    Sidebar content
    <input type="text"/>
  </nav>
  <button class="menu-button">☰</button>
  Body content goes here, Lorem ipsum sit amet, etc
</body>

Solution 78 - Javascript

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

Solution 79 - Javascript

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

Solution 80 - Javascript

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

Solution 81 - Javascript

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')
	}
}

Solution 82 - Javascript

The easiest way: mouseleave(function())

More info: https://www.w3schools.com/jquery/jquery_events.asp

Solution 83 - Javascript

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

Demo

<div tabindex="1">
    Focus me
</div>

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

Solution 84 - Javascript

 <div class="feedbackCont" onblur="hidefeedback();">
        <div class="feedbackb" onclick="showfeedback();" ></div>
        <div class="feedbackhide" tabindex="1"> </div>
 </div>

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.

Solution 85 - Javascript

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);
}

Solution 86 - Javascript

Standard HTML:

Surround the menus by a <label> and fetch focus state changes.

http://jsfiddle.net/bK3gL/

Plus: you can unfold the menu by Tab.

Solution 87 - Javascript

Using not():

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

Solution 88 - Javascript

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

Solution 89 - Javascript

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

Solution 90 - Javascript

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
});

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSergio del AmoView Question on Stackoverflow
Solution 1 - JavascriptEran GalperinView Answer on Stackoverflow
Solution 2 - JavascriptArtView Answer on Stackoverflow
Solution 3 - JavascriptzzzzBovView Answer on Stackoverflow
Solution 4 - JavascriptDennisView Answer on Stackoverflow
Solution 5 - JavascriptJoe LencioniView Answer on Stackoverflow
Solution 6 - JavascriptCezar AugustoView Answer on Stackoverflow
Solution 7 - JavascriptRameez RamiView Answer on Stackoverflow
Solution 8 - Javascriptuser212621View Answer on Stackoverflow
Solution 9 - JavascriptWolframView Answer on Stackoverflow
Solution 10 - JavascriptsrinathView Answer on Stackoverflow
Solution 11 - JavascriptJitendra DamorView Answer on Stackoverflow
Solution 12 - Javascript34m0View Answer on Stackoverflow
Solution 13 - JavascriptbenbView Answer on Stackoverflow
Solution 14 - JavascriptChris MacDonaldView Answer on Stackoverflow
Solution 15 - JavascriptIman SedighiView Answer on Stackoverflow
Solution 16 - JavascriptJovanni GView Answer on Stackoverflow
Solution 17 - JavascriptChu YeowView Answer on Stackoverflow
Solution 18 - JavascriptDan PhilipView Answer on Stackoverflow
Solution 19 - JavascriptBohdan LyzanetsView Answer on Stackoverflow
Solution 20 - Javascriptnazar kuliyevView Answer on Stackoverflow
Solution 21 - Javascripttim-mccurrachView Answer on Stackoverflow
Solution 22 - Javascriptuser4639281View Answer on Stackoverflow
Solution 23 - JavascriptErikView Answer on Stackoverflow
Solution 24 - JavascriptwebenformasyonView Answer on Stackoverflow
Solution 25 - JavascriptmemsView Answer on Stackoverflow
Solution 26 - JavascriptWaltView Answer on Stackoverflow
Solution 27 - JavascriptDuannxView Answer on Stackoverflow
Solution 28 - JavascriptRinto GeorgeView Answer on Stackoverflow
Solution 29 - JavascriptИлья ЗеленькоView Answer on Stackoverflow
Solution 30 - JavascriptRowanView Answer on Stackoverflow
Solution 31 - JavascriptSalman AView Answer on Stackoverflow
Solution 32 - JavascriptbbeView Answer on Stackoverflow
Solution 33 - JavascriptSatya PrakashView Answer on Stackoverflow
Solution 34 - JavascriptScott RichardsonView Answer on Stackoverflow
Solution 35 - JavascriptMatthew GoodwinView Answer on Stackoverflow
Solution 36 - JavascriptNecoView Answer on Stackoverflow
Solution 37 - JavascriptSpencer FryView Answer on Stackoverflow
Solution 38 - JavascriptBilal BerjawiView Answer on Stackoverflow
Solution 39 - JavascriptkboomView Answer on Stackoverflow
Solution 40 - JavascriptWebmaster GView Answer on Stackoverflow
Solution 41 - JavascriptFabianView Answer on Stackoverflow
Solution 42 - JavascriptDaniG2kView Answer on Stackoverflow
Solution 43 - JavascriptYair CohenView Answer on Stackoverflow
Solution 44 - JavascriptteynonView Answer on Stackoverflow
Solution 45 - JavascriptAndersView Answer on Stackoverflow
Solution 46 - JavascriptManish ShrivastavaView Answer on Stackoverflow
Solution 47 - JavascriptLucasView Answer on Stackoverflow
Solution 48 - JavascriptKarthikeyan GanesanView Answer on Stackoverflow
Solution 49 - Javascripthienbt88View Answer on Stackoverflow
Solution 50 - JavascriptMuhammet Can TONBULView Answer on Stackoverflow
Solution 51 - Javascriptonline ThomasView Answer on Stackoverflow
Solution 52 - JavascriptNormajeanView Answer on Stackoverflow
Solution 53 - JavascriptSommelierView Answer on Stackoverflow
Solution 54 - JavascriptgovindView Answer on Stackoverflow
Solution 55 - JavascriptnetdjwView Answer on Stackoverflow
Solution 56 - JavascriptToogyView Answer on Stackoverflow
Solution 57 - JavascriptAlexandre T.View Answer on Stackoverflow
Solution 58 - JavascriptmadayView Answer on Stackoverflow
Solution 59 - JavascriptWaheedView Answer on Stackoverflow
Solution 60 - JavascriptWaltur BuerkView Answer on Stackoverflow
Solution 61 - Javascriptchea sothearaView Answer on Stackoverflow
Solution 62 - JavascriptMarcelo RibeiroView Answer on Stackoverflow
Solution 63 - JavascriptMu-Tsun TsaiView Answer on Stackoverflow
Solution 64 - JavascriptRoei BahumiView Answer on Stackoverflow
Solution 65 - JavascriptThamaraiselvamView Answer on Stackoverflow
Solution 66 - JavascriptfroilanqView Answer on Stackoverflow
Solution 67 - JavascriptmlangenbergView Answer on Stackoverflow
Solution 68 - JavascriptAwenaView Answer on Stackoverflow
Solution 69 - JavascriptDaniel TononView Answer on Stackoverflow
Solution 70 - JavascriptwscView Answer on Stackoverflow
Solution 71 - JavascriptYishu FangView Answer on Stackoverflow
Solution 72 - JavascriptQwertiyView Answer on Stackoverflow
Solution 73 - JavascriptFDiskView Answer on Stackoverflow
Solution 74 - JavascriptAominéView Answer on Stackoverflow
Solution 75 - JavascriptakslView Answer on Stackoverflow
Solution 76 - Javascriptaxew3View Answer on Stackoverflow
Solution 77 - JavascriptjameshfisherView Answer on Stackoverflow
Solution 78 - JavascriptFelix FurtmayrView Answer on Stackoverflow
Solution 79 - JavascriptKyleMitView Answer on Stackoverflow
Solution 80 - JavascriptNitekursView Answer on Stackoverflow
Solution 81 - JavascriptRivenfallView Answer on Stackoverflow
Solution 82 - JavascriptJBarrosView Answer on Stackoverflow
Solution 83 - JavascriptYacine ZalouaniView Answer on Stackoverflow
Solution 84 - JavascriptconstrictusView Answer on Stackoverflow
Solution 85 - Javascriptlan.taView Answer on Stackoverflow
Solution 86 - JavascriptGrimView Answer on Stackoverflow
Solution 87 - JavascriptshivView Answer on Stackoverflow
Solution 88 - JavascriptMahesh GaikwadView Answer on Stackoverflow
Solution 89 - JavascriptaroykosView Answer on Stackoverflow
Solution 90 - JavascriptmartinedwardsView Answer on Stackoverflow