By checking whether element is clicked or its surroundings
In this method, we will check whether the click is occurred inside the element or outside using the is() and the has() methods of jQuery.
Syntax:
$(selected_element).is()
$(selected_element).has()
Example: The below method checks whether the click occurred outside or inside the element using the is() and has() methods.
html
<!DOCTYPE html> < html > < head > < title > How to hide a div when the user clicks outside of it using jQuery? </ title > < style > .container { height: 200px; width: 200px; background-color: green; border: 5px solid black; } </ style > < script src = "https://code.jquery.com/jquery-3.4.0.min.js" > </ script > </ head > < body > < center > < h1 style = "color: green" > w3wiki </ h1 > < b > How to hide a div when the user clicks outside of it using jQuery? </ b > < p > Click outside the green div to hide it </ p > < div class = "container" style = "color:green" > </ div > </ center > < script type = "text/javascript" > $(document).mouseup(function (e) { var container = $(".container"); if (!container. is(e.target) && container. has(e.target). length === 0) { container.hide(); } }); </ script > </ body > </ html > |
Output:
jQuery is an open source JavaScript library that simplifies the interactions between an HTML/CSS document, It is widely famous with it’s philosophy of “Write less, do more”. You can learn jQuery from the ground up by following this jQuery Tutorial and jQuery Examples.
How to hide a div when the user clicks outside of it using jQuery?
In this article, we will learn how an element can be hidden on click to its surroundings using jQuery. An element can be shown or hidden when clicked outside of it using the methods discussed below:
Table of Content
- Using the closest() method
- By checking whether element is clicked or its surroundings