Use jQuery to hide a DIV when the user clicks outside of it

JqueryHtmlHideStyling

Jquery Problem Overview


I am using this code:

$('body').click(function() {
   $('.form_wrapper').hide();
});

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

And this HTML:

<div class="form_wrapper">
   <a class="agree" href="javascript:;">I Agree</a>
   <a class="disagree" href="javascript:;">Disagree</a>
</div>

The problem is that I have links inside the div and when they no longer work when clicked.

Jquery Solutions


Solution 1 - Jquery

Had the same problem, came up with this easy solution. It's even working recursive:

$(document).mouseup(function(e) 
{
    var container = $("YOUR CONTAINER SELECTOR");

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

Solution 2 - Jquery

You'd better go with something like this:

var mouse_is_inside = false;

$(document).ready(function()
{
    $('.form_content').hover(function(){ 
        mouse_is_inside=true; 
    }, function(){ 
        mouse_is_inside=false; 
    });

    $("body").mouseup(function(){ 
        if(! mouse_is_inside) $('.form_wrapper').hide();
    });
});

Solution 3 - Jquery

This code detects any click event on the page and then hides the #CONTAINER element if and only if the element clicked was neither the #CONTAINER element nor one of its descendants.

$(document).on('click', function (e) {
    if ($(e.target).closest("#CONTAINER").length === 0) {
        $("#CONTAINER").hide();
    }
});

Solution 4 - Jquery

You might want to check the target of the click event that fires for the body instead of relying on stopPropagation.

Something like:

$("body").click
(
  function(e)
  {
    if(e.target.className !== "form_wrapper")
    {
      $(".form_wrapper").hide();
    }
  }
);

Also, the body element may not include the entire visual space shown in the browser. If you notice that your clicks are not registering, you may need to add the click handler for the HTML element instead.

Solution 5 - Jquery

Live DEMO

Check click area is not in the targeted element or in it's child

$(document).click(function (e) {
    if ($(e.target).parents(".dropdown").length === 0) {
        $(".dropdown").hide();
    }
});

UPDATE:

jQuery stop propagation is the best solution

Live DEMO

$(".button").click(function(e){
    $(".dropdown").show();
     e.stopPropagation();
});

$(".dropdown").click(function(e){
    e.stopPropagation();
});

$(document).click(function(){
    $(".dropdown").hide();
});

Solution 6 - Jquery

$(document).click(function(event) {
    if ( !$(event.target).hasClass('form_wrapper')) {
         $(".form_wrapper").hide();
    }
});

Solution 7 - Jquery

A solution without jQuery for the most popular answer:

document.addEventListener('mouseup', function (e) {
	var container = document.getElementById('your container ID');

	if (!container.contains(e.target)) {
		container.style.display = 'none';
	}
}.bind(this));

MDN: https://developer.mozilla.org/en/docs/Web/API/Node/contains

Solution 8 - Jquery

Updated the solution to:

  • use mouseenter and mouseleave instead
  • of hover use live event binding

var mouseOverActiveElement = false;

$('.active').live('mouseenter', function(){
    mouseOverActiveElement = true; 
}).live('mouseleave', function(){ 
    mouseOverActiveElement = false; 
});
$("html").click(function(){ 
    if (!mouseOverActiveElement) {
        console.log('clicked outside active element');
    }
});

Solution 9 - Jquery

Live demo with ESC functionality

Works on both Desktop and Mobile

var notH = 1,
    $pop = $('.form_wrapper').hover(function(){ notH^=1; });

$(document).on('mousedown keydown', function( e ){
  if(notH||e.which==27) $pop.hide();
});

If for some case you need to be sure that your element is really visible when you do clicks on the document: if($pop.is(':visible') && (notH||e.which==27)) $pop.hide();

Solution 10 - Jquery

Wouldn't something like this work?

$("body *").not(".form_wrapper").click(function() {

});

or

$("body *:not(.form_wrapper)").click(function() {

});

Solution 11 - Jquery

Instead of listening to every single click on the DOM to hide one specific element, you could set tabindex to the parent <div> and listen to the focusout events.

Setting tabindex will make sure that the blur event is fired on the <div> (normally it wouldn't).

So your HTML would look like:

<div class="form_wrapper" tabindex="0">
    <a class="agree" href="javascript:;">I Agree</a>
    <a class="disagree" href="javascript:;">Disagree</a>
</div>

And your JS:

$('.form_wrapper').on('focusout', function(event){
    $('.form_wrapper').hide();
});

Solution 12 - Jquery

Even sleaker:

$("html").click(function(){ 
    $(".wrapper:visible").hide();
});

Solution 13 - Jquery

So many answers, must be a right of passage to have added one... I didn't see a current (jQuery 3.1.1) answers - so:

$(function() {
    $('body').on('mouseup', function() {
        $('#your-selector').hide();
    });
});

Solution 14 - Jquery

Here's a jsfiddle I found on another thread, works with esc key also: http://jsfiddle.net/S5ftb/404

    var button = $('#open')[0]
    var el     = $('#test')[0]

    $(button).on('click', function(e) {
      $(el).show()
      e.stopPropagation()
    })

    $(document).on('click', function(e) {
      if ($(e.target).closest(el).length === 0) {
        $(el).hide()
      }
    })

    $(document).on('keydown', function(e) {
      if (e.keyCode === 27) {
        $(el).hide()
      }
    })

Solution 15 - Jquery

And for Touch devices like IPAD and IPHONE we can use following 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 16 - Jquery

(Just adding on to prc322's answer.)

In my case I'm using this code to hide a navigation menu that appears when the user clicks an appropriate tab. I found it was useful to add an extra condition, that the target of the click outside the container is not a link.

$(document).mouseup(function (e)
{
    var container = $("YOUR CONTAINER SELECTOR");

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

This is because some of the links on my site add new content to the page. If this new content is added at the same time that the navigation menu disappears it might be disorientating for the user.

Solution 17 - Jquery

Built off of prc322's awesome answer.

function hideContainerOnMouseClickOut(selector, callback) {
  var args = Array.prototype.slice.call(arguments); // Save/convert arguments to array since we won't be able to access these within .on()
  $(document).on("mouseup.clickOFF touchend.clickOFF", function (e) {
    var 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();
      $(document).off("mouseup.clickOFF touchend.clickOFF");
      if (callback) callback.apply(this, args);
    }
  });
}

This adds a couple things...

  1. Placed within a function with a callback with "unlimited" args
  2. Added a call to jquery's .off() paired with a event namespace to unbind the event from the document once it's been run.
  3. Included touchend for mobile functionality

I hope this helps someone!

Solution 18 - Jquery

if you have trouble with ios, mouseup is not working on apple device.

<https://stackoverflow.com/questions/3303469/does-mousedown-mouseup-in-jquery-work-for-the-ipad>

i use this:

$(document).bind('touchend', function(e) {
        var container = $("YOURCONTAINER");

          if (container.has(e.target).length === 0)
          {
              container.hide();
          }
      });

Solution 19 - Jquery

var n = 0;
$("#container").mouseenter(function() {
n = 0;

}).mouseleave(function() {
n = 1;
});

$("html").click(function(){ 
if (n == 1) {
alert("clickoutside");
}
});

Solution 20 - Jquery

 $('body').click(function(event) {
    if (!$(event.target).is('p'))
    {
        $("#e2ma-menu").hide();
    }
});

p is the element name. Where one can pass the id or class or element name also.

Solution 21 - Jquery

Copied from https://sdtuts.com/click-on-not-specified-element/

Live demo http://demos.sdtuts.com/click-on-specified-element

$(document).ready(function () {
	var is_specified_clicked;
	$(".specified_element").click(function () {
		is_specified_clicked = true;
		setTimeout(function () {
			is_specified_clicked = false;
		}, 200);
	})
	$("*").click(function () {
		if (is_specified_clicked == true) {
//WRITE CODE HERE FOR CLICKED ON OTHER ELEMENTS
			$(".event_result").text("you were clicked on specified element");
		} else {
//WRITE CODE HERE FOR SPECIFIED ELEMENT CLICKED
			$(".event_result").text("you were clicked not on specified element");
		}
	})
})

Solution 22 - Jquery

Return false if you click on .form_wrapper:

$('body').click(function() {
  $('.form_wrapper').click(function(){
  return false
});
   $('.form_wrapper').hide();
});

//$('.form_wrapper').click(function(event){
//   event.stopPropagation();
//});

Solution 23 - Jquery

Attach a click event to top level elements outside the form wrapper, for example:

$('#header, #content, #footer').click(function(){
    $('.form_wrapper').hide();
});

This will also work on touch devices, just make sure you don't include a parent of .form_wrapper in your list of selectors.

Solution 24 - Jquery

var exclude_div = $("#ExcludedDiv");;  
$(document).click(function(e){
   if( !exclude_div.is( e.target ) )  // if target div is not the one you want to exclude then add the class hidden
        $(".myDiv1").addClass("hidden");  

}); 

FIDDLE

Solution 25 - Jquery

$(document).ready(function() {
	$('.modal-container').on('click', function(e) {
	  if(e.target == $(this)[0]) {
		$(this).removeClass('active'); // or hide()
	  }
	});
});

.modal-container {
	display: none;
	justify-content: center;
	align-items: center;
	position: absolute;
	top: 0;
	left: 0;
	right: 0;
	bottom: 0;
	background-color: rgba(0,0,0,0.5);
	z-index: 999;
}

.modal-container.active {
    display: flex;  
}

.modal {
	width: 50%;
	height: auto;
	margin: 20px;
	padding: 20px;
	background-color: #fff;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="modal-container active">
	<div class="modal">
		<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean ac varius purus. Ut consectetur viverra nibh nec maximus. Nam luctus ligula quis arcu accumsan euismod. Pellentesque imperdiet volutpat mi et cursus. Sed consectetur sed tellus ut finibus. Suspendisse porttitor laoreet lobortis. Nam ut blandit metus, ut interdum purus.</p>
	</div>
</div>

Solution 26 - Jquery

What you can do is bind a click event to the document that will hide the dropdown if something outside the dropdown is clicked, but won't hide it if something inside the dropdown is clicked, so your "show" event (or slidedown or whatever shows the dropdown)

    $('.form_wrapper').show(function(){

        $(document).bind('click', function (e) {
            var clicked = $(e.target);
            if (!clicked.parents().hasClass("class-of-dropdown-container")) {
                 $('.form_wrapper').hide();
            }
        });

    });

Then when hiding it, unbind the click event

$(document).unbind('click');

Solution 27 - Jquery

i did it like this:

var close = true;

$(function () {
 
    $('body').click (function(){

        if(close){
            div.hide();
        }
        close = true;
    })


alleswasdenlayeronclicknichtschliessensoll.click( function () {   
        close = false;
    });

});

Solution 28 - Jquery

dojo.query(document.body).connect('mouseup',function (e)
{
	var obj = dojo.position(dojo.query('div#divselector')[0]);
	if (!((e.clientX > obj.x && e.clientX <(obj.x+obj.w)) && (e.clientY > obj.y && e.clientY <(obj.y+obj.h))) ){
		MyDive.Hide(id);
	}
});

Solution 29 - Jquery

By using this code you can hide as many items as you want

var boxArray = ["first element's id","second element's id","nth element's id"];
   window.addEventListener('mouseup', function(event){
   for(var i=0; i < boxArray.length; i++){
    var box = document.getElementById(boxArray[i]);
    if(event.target != box && event.target.parentNode != box){
        box.style.display = 'none';
    }
   }
})

Solution 30 - Jquery

According to the docs, .blur() works for more than the <input> tag. For example:

$('.form_wrapper').blur(function(){
   $(this).hide();
});

Solution 31 - Jquery

You might encounter some issues when using the accepted answer with pop-up windows. There might be a case where clicking on a random place might result in unwanted actions, i.e. clicking on a button by mistake might take you to a new page.

I am not sure if this is the most efficient solution but to prevent this I would suggest using a screenmask. Make sure the screenmask is right below the <body> tag so that it can cover all the screen by width:100%; height: 100%. Also note that it is above all elements by z-index: 99. If you want another item or div to be clickable when the screenmask is active, just assign a higher z-index to that item or div.

The screenmask is initially not-displayed (displayed:none) and it calls a hide function when clicked (onclick="hidemenu()").

<body>
<div class="screenmask" onclick="hidemenu()" style="position:fixed; width: 100%; height: 100%; top: 0px; right: 0px; display: none; z-index: 99;"></div>

The javascript functions to deal with "multiple distinct pop-up menus on the same page" might be like the ones below:

<script>
// an element with onclick="showmenu('id_here')" pops a menu in the screen
function showmenu(id) {  
  var popmenu = document.getElementById(id); // assume popmenu is of class .cardmenu
  $('.cardmenu').hide();   // clear the screen from other popmenus first
  $(popmenu).show();          // pop the desired specific menu
  $('.screenmask').show(); // activate screenmask
}
    
function hidemenu() {      // called when clicked on the screenmask
  $('.cardmenu').hide();   // clear the screen from all the popmenus
  $('.screenmask').hide(); // deactivate screenmask
}
</script>

Solution 32 - Jquery

<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js">
</script>
<script>
$(document).ready(function(){
  $("#hide").click(function(){
    $("p").hide();
  });
  $("#show").click(function(){
    $("p").show();
  });
});
</script>
</head>
<body>
<p>If you click on the "Hide" button, I will disappear.</p>
<button id="hide">Hide</button>
<button id="show">Show</button>
</body>
</html>

Solution 33 - Jquery

Toggle for regular and touch devices

I read some answers here a while back and created some code I use for div's that function as popup bubbles.

$('#openPopupBubble').click(function(){
	$('#popupBubble').toggle();
	
	if($('#popupBubble').css('display') === 'block'){
		$(document).bind('mousedown touchstart', function(e){
			if($('#openPopupBubble').is(e.target) || $('#openPopupBubble').find('*').is(e.target)){
				$(this).unbind(e);
			} 
			else if(!$('#popupBubble').find('*').is(e.target)){
				$('#popupBubble').hide();
				$(this).unbind(e);
			}
		});
	}
});

You can also make this more abstract using classes and select the correct popup bubble based on the button that triggered the click event.

$('body').on('click', '.openPopupBubble', function(){
	$(this).next('.popupBubble').toggle();
	
	if($(this).next('.popupBubble').css('display') === 'block'){
		$(document).bind('mousedown touchstart', function(e){
			if($(this).is(e.target) || $(this).find('*').is(e.target)){
				$(this).unbind(e);
			} 
			else if(!$(this).next('.popupBubble').find('*').is(e.target)){
				$(this).next('.popupBubble').hide();
				$(this).unbind(e);
			}
		});
	}
});

Solution 34 - Jquery

This solution should work fine, it's easy :

jQuery(document).ready(function($) {
    jQuery(document).click(function(event) {
        if(typeof  jQuery(event.target).attr("class") != "undefined") {
            var classnottobeclickforclose = ['donotcountmeforclickclass1', 'donotcountmeforclickclass2','donotcountmeforclickclass3'];
            var arresult = jQuery.inArray(jQuery(event.target).attr("class"), classnottobeclickforclose);
            if (arresult < 0) {
                jQuery(".popup").hide();
            }
        }
    });
});

In Above code change donotcountmeforclickclass1 , donotcountmeforclickclass2 etc with classes which you have used to show popup or on it's click popup should not effect so you have to definitely add class which you are using to open popup.

Change .popup class with popup class.

Solution 35 - Jquery

I was working over a search box which shows the autocomplete according to the processed keywords. When i dont want to click over any option then i will use the below code to hide the processed list and it works.

$(document).click(function() {
 $('#suggestion-box').html("");
});

Suggestion-box is my autocomplete container where i am showing the values.

Solution 36 - Jquery

$(document).ready(function() {

$('.headings').click(function () {$('#sub1').css("display",""); });
$('.headings').click(function () {return false;});
$('#sub1').click(function () {return false;});
$('body').click(function () {$('#sub1').css("display","none");

})});

Solution 37 - Jquery

I think it can be a lot easier. I did it like this:

$(':not(.form_wrapper)').click(function() {
    $('.form_wrapper').hide();
});

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
QuestionScott Yu - builds stuffView Question on Stackoverflow
Solution 1 - Jqueryuser659025View Answer on Stackoverflow
Solution 2 - JqueryMakram SalehView Answer on Stackoverflow
Solution 3 - JqueryCaseView Answer on Stackoverflow
Solution 4 - JqueryDavid AndresView Answer on Stackoverflow
Solution 5 - JqueryMaxEchoView Answer on Stackoverflow
Solution 6 - Jquerymeder omuralievView Answer on Stackoverflow
Solution 7 - JqueryMartyIXView Answer on Stackoverflow
Solution 8 - JquerybenvdsView Answer on Stackoverflow
Solution 9 - JqueryRoko C. BuljanView Answer on Stackoverflow
Solution 10 - JqueryMRVDOGView Answer on Stackoverflow
Solution 11 - JqueryOscarView Answer on Stackoverflow
Solution 12 - JqueryOlivenbaumView Answer on Stackoverflow
Solution 13 - JqueryzakView Answer on Stackoverflow
Solution 14 - JquerydjvView Answer on Stackoverflow
Solution 15 - JqueryCode SpyView Answer on Stackoverflow
Solution 16 - JqueryshngrdnrView Answer on Stackoverflow
Solution 17 - JqueryWiseOlManView Answer on Stackoverflow
Solution 18 - Jqueryuser2271066View Answer on Stackoverflow
Solution 19 - JqueryGaryView Answer on Stackoverflow
Solution 20 - JqueryAbhishekView Answer on Stackoverflow
Solution 21 - Jqueryuser3151197View Answer on Stackoverflow
Solution 22 - JquerybogoView Answer on Stackoverflow
Solution 23 - JqueryThornberryPieView Answer on Stackoverflow
Solution 24 - JquerySharmaPattarView Answer on Stackoverflow
Solution 25 - JqueryRustBeardView Answer on Stackoverflow
Solution 26 - JqueryjeffsaraccoView Answer on Stackoverflow
Solution 27 - Jqueryuser2822517View Answer on Stackoverflow
Solution 28 - JqueryAbed YaseenView Answer on Stackoverflow
Solution 29 - JqueryMahdi YounesiView Answer on Stackoverflow
Solution 30 - JqueryBizleyView Answer on Stackoverflow
Solution 31 - JqueryXfce4View Answer on Stackoverflow
Solution 32 - JqueryBhushan waghView Answer on Stackoverflow
Solution 33 - JqueryScepticView Answer on Stackoverflow
Solution 34 - JqueryDen PatView Answer on Stackoverflow
Solution 35 - JqueryVivekView Answer on Stackoverflow
Solution 36 - JqueryPeterView Answer on Stackoverflow
Solution 37 - JquerySPRBRNView Answer on Stackoverflow