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
});
This question is related to
javascript
jquery
click
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.
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);
}
})
});
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");
}
});
const button = document.querySelector('button')_x000D_
const box = document.querySelector('.box');_x000D_
_x000D_
const toggle = event => {_x000D_
event.stopPropagation();_x000D_
_x000D_
if (!event.target.closest('.box')) {_x000D_
console.log('Click outside');_x000D_
_x000D_
box.classList.toggle('active');_x000D_
_x000D_
box.classList.contains('active')_x000D_
? document.addEventListener('click', toggle)_x000D_
: document.removeEventListener('click', toggle);_x000D_
} else {_x000D_
console.log('Click inside');_x000D_
}_x000D_
}_x000D_
_x000D_
button.addEventListener('click', toggle);
_x000D_
.box {_x000D_
position: absolute;_x000D_
display: none;_x000D_
margin-top: 8px;_x000D_
padding: 20px;_x000D_
background: lightgray;_x000D_
}_x000D_
_x000D_
.box.active {_x000D_
display: block;_x000D_
}
_x000D_
<button>Toggle box</button>_x000D_
_x000D_
<div class="box">_x000D_
<form action="">_x000D_
<input type="text">_x000D_
<button type="button">Search</button>_x000D_
</form>_x000D_
</div>
_x000D_
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;
}
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();
});
});
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(){_x000D_
$("#element").animate({width: 'toggle'});_x000D_
$("#outside-element").show();_x000D_
});_x000D_
$("#outside-element").click(function(){_x000D_
$("#element").hide();_x000D_
$("#outside-element").hide();_x000D_
});
_x000D_
#outside-element {_x000D_
position:fixed;_x000D_
width:100%;_x000D_
height:100%;_x000D_
z-index:1;_x000D_
display:none;_x000D_
}_x000D_
#element {_x000D_
display:none;_x000D_
padding:20px;_x000D_
background-color:#ccc;_x000D_
width:300px;_x000D_
z-index:2;_x000D_
position:relative;_x000D_
}_x000D_
#show-trigger {_x000D_
padding:20px;_x000D_
background-color:#ccc;_x000D_
margin:20px auto;_x000D_
z-index:2;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div id="outside-element"></div>_x000D_
<div id="element">_x000D_
<div class="menu-item"><a href="#1">Menu Item 1</a></div>_x000D_
<div class="menu-item"><a href="#2">Menu Item 1</a></div>_x000D_
<div class="menu-item"><a href="#3">Menu Item 1</a></div>_x000D_
<div class="menu-item"><a href="#4">Menu Item 1</a></div>_x000D_
</div>_x000D_
<div id="show-trigger">Show Menu</div>
_x000D_
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.
$('html').click(function() {_x000D_
//Hide the menus if visible_x000D_
});_x000D_
_x000D_
$('#menucontainer').click(function(event){_x000D_
event.stopPropagation();_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<html>_x000D_
<button id='#menucontainer'>Ok</button> _x000D_
</html>
_x000D_
Using not():
$("#id").not().click(function() {
alert('Clicked other that #id');
});
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";
}
});
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
}
});
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');
});
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();
}
});
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()
If you are using tools like "Pop-up", you can use the "onFocusOut" event.
window.onload=function(){_x000D_
document.getElementById("inside-div").focus();_x000D_
}_x000D_
function loseFocus(){_x000D_
alert("Clicked outside");_x000D_
}
_x000D_
#container{_x000D_
background-color:lightblue;_x000D_
width:200px;_x000D_
height:200px;_x000D_
}_x000D_
_x000D_
#inside-div{_x000D_
background-color:lightgray;_x000D_
width:100px;_x000D_
height:100px;_x000D_
_x000D_
}
_x000D_
<div id="container">_x000D_
<input type="text" id="inside-div" onfocusout="loseFocus()">_x000D_
</div>
_x000D_
$(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.
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.
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>
After research I have found three working solutions (I forgot the page links for reference)
<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>
<script>
$('body').on('click', function(e) {
if($(e.target).closest('#testDiv').length == 0) {
/* Hide dropdown here */
}
});
</script>
<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>
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();
}
});
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
});
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");
You can set a tabindex to the DOM element. This will trigger a blur event when the user click outside the DOM element.
<div tabindex="1">
Focus me
</div>
document.querySelector("div").onblur = function(){
console.log('clicked outside')
}
document.querySelector("div").onfocus = function(){
console.log('clicked inside')
}
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';
}
});
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'));
_x000D_
.block {
width: 400px;
height: 400px;
background-color: red;
}
_x000D_
<div class="block"></div>
_x000D_
jQuery().ready(function(){
$('#nav').click(function (event) {
$(this).addClass('activ');
event.stopPropagation();
});
$('html').click(function () {
if( $('#nav').hasClass('activ') ){
$('#nav').removeClass('activ');
}
});
});
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
}
});
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
});
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"!
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
eventA 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');
});
_x000D_
div {
display: none;
}
.active {
display: block;
}
_x000D_
<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>
_x000D_
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'));
}
});
_x000D_
div {
display: none;
}
.active {
display: block;
}
_x000D_
<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>
_x000D_
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'));
}
});
_x000D_
div {
display: none;
}
.active {
display: block;
}
_x000D_
<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>
_x000D_
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'));
}
});
_x000D_
div {
display: none;
}
.active {
display: block;
}
_x000D_
<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>
_x000D_
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();
}
}
});
_x000D_
.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;
}
_x000D_
<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.
_x000D_
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.
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
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.
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...
});
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();
}
});
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>
$(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.
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).
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.
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;
}
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')
}
}
$("html").click(function(){
if($('#info').css("opacity")>0.9) {
$('#info').fadeOut('fast');
}
});
2020 solution using native JS API closest method.
document.addEventListener('click', ({ target }) => {
if (!target.closest('.el1, .el2, #el3')) {
alert('click outside')
}
})
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.
The easiest way: mouseleave(function())
More info: https://www.w3schools.com/jquery/jquery_events.asp
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();
});
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();
}
$("body > div:not(#dvid)").click(function (e) {
//your code
});
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}
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 OR
ing the element check in the some
function.
$("body").click(function() {_x000D_
target = document.getElementById("main");_x000D_
flag = event.path.some(function(el, i, arr) {_x000D_
return (el == target)_x000D_
})_x000D_
if (flag) {_x000D_
console.log("Inside")_x000D_
} else {_x000D_
console.log("Outside")_x000D_
}_x000D_
});
_x000D_
#main {_x000D_
display: inline-block;_x000D_
background:yellow;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div id="main">_x000D_
<ul>_x000D_
<li>Test-Main</li>_x000D_
<li>Test-Main</li>_x000D_
<li>Test-Main</li>_x000D_
<li>Test-Main</li>_x000D_
<li>Test-Main</li>_x000D_
</ul>_x000D_
</div>_x000D_
<div id="main2">_x000D_
Outside Main_x000D_
</div>
_x000D_
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
}
});
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.
Now there is a plugin for that: outside events (blog post)
The following happens when a clickoutside handler (WLOG) is bound to an element:
So no events are stopped from propagation and additional click handlers may be used "above" the element with the outside-handler.
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();
}
});
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
$(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
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.
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();
}
});
<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.
$('#menucontainer').click(function(e){
e.stopPropagation();
});
$(document).on('click', function(e){
// code
});
This worked perfectly fine in time for me:
$('body').click(function() {
// Hide the menus if visible.
});
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/
The other solutions here didn't work for me so I had to use:
if(!$(event.target).is('#foo'))
{
// hide menu
}
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:
body { margin-left:auto; margin-right: auto; width:960px;}
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'
}
})
_x000D_
/* 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;
}
_x000D_
<div id="myTarget">
click me (or not!)
</div>
_x000D_
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 = '';
});
_x000D_
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
</head>
<body>
<button id="button">Click</button>
</body>
</html>
_x000D_
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);
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.
One more solution is here:
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);
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);
}
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();
});
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
$("#menuscontainer").click(function() {
$(this).focus();
});
$("#menuscontainer").blur(function(){
$(this).hide();
});
Works for me just fine.
$('#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);
});
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();
});
This worked for me perfectly!!
$('html').click(function (e) {
if (e.target.id == 'YOUR-DIV-ID') {
//do something
} else {
//do something
}
});
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.
Standard HTML:
Surround the menus by a <label>
and fetch focus state changes.
Plus: you can unfold the menu by Tab.
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();
});
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.
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;}
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()
).
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 () {_x000D_
"use strict";_x000D_
var hidden = document.getElementById('hidden');_x000D_
document.addEventListener('click', function (e) {_x000D_
if (e.target.id == 'toggle' || (hidden.style.display != 'none' && !hidden.contains(e.target))) hidden.style.display = hidden.style.display == 'none' ? 'block' : 'none';_x000D_
}, false);_x000D_
})();
_x000D_
<a href="javascript:void(0)" id="toggle">Toggle Hidden Div</a>_x000D_
<div id="hidden" style="display: none;">This content is normally hidden. click anywhere other than this content to make me disappear</div>
_x000D_
If you are going to have multiple toggles on the same page you can use something like this:
hidden
to the collapsible item.(function () {_x000D_
"use strict";_x000D_
var hiddenItems = document.getElementsByClassName('hidden'), hidden;_x000D_
document.addEventListener('click', function (e) {_x000D_
for (var i = 0; hidden = hiddenItems[i]; i++) {_x000D_
if (!hidden.contains(e.target) && hidden.style.display != 'none')_x000D_
hidden.style.display = 'none';_x000D_
}_x000D_
if (e.target.getAttribute('data-toggle')) {_x000D_
var toggle = document.querySelector(e.target.getAttribute('data-toggle'));_x000D_
toggle.style.display = toggle.style.display == 'none' ? 'block' : 'none';_x000D_
}_x000D_
}, false);_x000D_
})();
_x000D_
<a href="javascript:void(0)" data-toggle="#hidden1">Toggle Hidden Div</a>_x000D_
<div class="hidden" id="hidden1" style="display: none;" data-hidden="true">This content is normally hidden</div>_x000D_
<a href="javascript:void(0)" data-toggle="#hidden2">Toggle Hidden Div</a>_x000D_
<div class="hidden" id="hidden2" style="display: none;" data-hidden="true">This content is normally hidden</div>_x000D_
<a href="javascript:void(0)" data-toggle="#hidden3">Toggle Hidden Div</a>_x000D_
<div class="hidden" id="hidden3" style="display: none;" data-hidden="true">This content is normally hidden</div>
_x000D_
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();
}
});
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)
}
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()
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()
}
}
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;
})
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;
}
}
};
})();
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
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>
Source: Stackoverflow.com