Hide a div on clicking outside it with JavaScript/jQuery
This post will discuss how to hide a div container if a user clicks anywhere on the page outside it in JavaScript and jQuery.
1. Using jQuery
With jQuery, you can bind to the document’s click event and hides the div container when the clicked element isn’t the container itself or a descendant of the div element. This can be implemented as following with jQuery:
jQuery
|
1 2 3 4 5 6 |
$(document).click(function() { var container = $("#container"); if (!container.is(event.target) && !container.has(event.target).length) { container.hide(); } }); |
HTML
|
1 2 3 4 5 |
<div id="container"> <label>Enter your name:</label> <input type="text"> <button id="submit">Submit</button> </div> |
Another plausible way is to use the .closest() method:
jQuery
|
1 2 3 4 5 6 |
$(document).on('click', function(e) { var container = $("#container"); if (!$(e.target).closest(container).length) { container.hide(); } }); |
HTML
|
1 2 3 4 5 |
<div id="container"> <label>Enter your name:</label> <input type="text"> <button id="submit">Submit</button> </div> |
2. Using JavaScript
Here, the idea is to detect click events on the page and set the container’s display to none only when the target of the click isn’t one of the div descendants.
JS
|
1 2 3 4 5 6 |
document.addEventListener('mouseup', function(e) { var container = document.getElementById('container'); if (!container.contains(e.target)) { container.style.display = 'none'; } }); |
HTML
|
1 2 3 4 5 |
<div id="container"> <label>Enter your name:</label> <input type="text"> <button id="submit">Submit</button> </div> |
That’s all about hiding a div on clicking outside it in JavaScript and jQuery.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)