How to Hide a Div When the User Clicks Outside of it using jQuery?

How to Hide a Div When the User Clicks Outside of it using jQuery?

You will come across the dropdown menus, modals, or tooltips that will disappear when the user clicks outside them when working with the webpage. It is the most common feature while developing the website. We will look into different methods to hide a div using jQuery, with examples in this blog.

Table of Contents:

Methods to Hide a Div when the User Clicks Outside of it Using jQuery

You can use methods like click(), closest(), is(), and had() together to hide a div when the user clicks outside of it using jQuery. Let’s discuss these functions below.

Method 1: Using Closest() method

When you click anywhere on the page, the script checks if the click happened inside the #myDiv. If you click outside of it, the div gets hidden. But if you click inside the div, it stays visible because the click event doesn’t reach the rest of the page.

Example:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Hide Div with closest()</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <style>
        #myDiv {
            width: 300px;
            height: 200px;
            background-color: lightcoral;
            position: absolute;
            top: 50px;
            left: 50px;
            padding: 20px;
            box-shadow: 0 0 10px rgba(0, 0, 0, 0.5);
        }
    </style>
</head>
<body>
    <button id="showDiv">Show Div</button>
    <div id="myDiv" style="display: none;">
        Click outside of this box to hide it.
    </div>

    <script>
        $(document).ready(function() {
            // Show the div when the button is clicked
            $('#showDiv').click(function() {
                $('#myDiv').show();
            });
            // Hide the div when clicking outside using closest() method
            $(document).click(function(event) {
                if (!$(event.target).closest("#myDiv, #showDiv").length) {
                    $("#myDiv").hide();
                }
            });
        });
    </script>
</body>
</html>

Output:

Using Closest() method Output

Explanation: When you click on the page, the code looks for the nearest ancestor that matches #myDiv or #showDiv using $(event.target).closest(“#myDiv, #showDiv”). If it doesn’t match, then myDiv gets hidden.

Method 2: Using click() Method

The jQuery click() method lets you set up a function that runs when someone clicks on an element. You can use this method to check if a user clicks anywhere on the page or just inside a certain element. It’s great for hiding a <div> when a user clicks outside of it.

Example:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Hide Div on Click Outside</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <style>
        #myDiv {
            width: 300px;
            height: 200px;
            background-color: lightblue;
            position: absolute;
            top: 50px;
            left: 50px;
            padding: 20px;
            box-shadow: 0 0 10px rgba(0, 0, 0, 0.5);
        }
    </style>
</head>
<body>
    <button id="showDiv">Show Div</button>
    <div id="myDiv" style="display: none;">
        Click outside of this box to hide it.
    </div>

    <script>
        $(document).ready(function() {
            // Show the div when the button is clicked
            $('#showDiv').click(function() {
                $('#myDiv').show();
            });

            // Hide the div when clicking outside using click() method
            $(document).click(function(event) {
                if (!$(event.target).is("#myDiv, #showDiv")) {
                    $("#myDiv").hide();
                }
            });
        });
    </script>
</body>
</html>

Output:

Using click() Method Output

Explanation: The click can be detected on the document using this method. The $(event.target).is(“#myDiv, #showDiv”) function is used to check if the click is on any of the div. If the clicked element is outside, #myDiv gets hidden.

Method 3: Using is() and has() Method

The is() and has() method is used for filtering and checking the elements based on the conditions. You can use this method together to determine whether a click is outside or inside of a target element.

Example:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Hide Div on Click Outside</title>
  <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
  <style>
    /* Styling the target div */
    #targetDiv {
      width: 300px;
      height: 200px;
      background-color: lightblue;
      margin: 100px auto;
      padding: 20px;
      text-align: center;
      box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
    }
    /* Styling for a message outside the target div */
    #outsideMessage {
      width: 100%;
      text-align: center;
      font-size: 18px;
      margin-top: 20px;
      color: #333;
    }
  </style>
</head>
<body>
  <div id="targetDiv">
    <h3>Click Outside This Div to Hide It</h3>
    <p>This div will be hidden when you click outside of it.</p>
  </div>
  <div id="outsideMessage">
    <p>Click outside the blue box above to hide it.</p>
  </div>
  <script>
    $(document).click(function(event) {
      // Check if the click is outside the #targetDiv
      if (!$(event.target).closest('#targetDiv').length) {
        // Hide the div if the click is outside
        $('#targetDiv').hide();
      }
    });

    // Prevent the click inside #targetDiv from propagating to the document
    $('#targetDiv').click(function(event) {
      event.stopPropagation();
    });
  </script>
</body>
</html>

Output:

Using is() and has() Method Output

Explanation: You can see the target div when you load the page. The hiding behaviour is not triggered in the case of the clicking inside the div, and if the click is outside the div, it gets hidden.

Conclusion

The above-discussed methods are the most effective to hide a div when clicking outside. You can use methods like click(), closest(), is(), and has() to easily hide a div when a user clicks outside of it using jQuery. This can be helpful for creating dropdown menus, modals, and other interactive elements on your web page.

How to Hide a Div When the User Clicks Outside of it Using jQuery? – FAQs

1. Why would I want to hide a div when a user clicks outside of it?

It can be helpful in creating dropdown menus, modals, and other interactive elements on your web page.

2. What jQuery methods can be used to achieve this?

You can use methods like click(), closest(), is(), and has() to hide a div when the user clicks outside of it using jQuery

3. How does the closest() method help?

This method checks if the clicked element or any of its ancestors matches the specified selector. If not, the div gets hidden.

4. How can the click() method be used?

This method allows you to set up the function that runs when the element is clicked. You can use it to detect clicks anywhere on the page or just inside a specific element, and then hide the div if the click is outside.

5. How do is() and has() methods work?

The is() method checks if an element matches a specified selector, and the has() method checks if an element contains another element. Together, they can be used to determine if a click is inside or outside the div.

About the Author

Technical Research Analyst - Full Stack Development

Kislay is a Technical Research Analyst and Full Stack Developer with expertise in crafting Mobile applications from inception to deployment. Proficient in Android development, IOS development, HTML, CSS, JavaScript, React, Angular, MySQL, and MongoDB, he’s committed to enhancing user experiences through intuitive websites and advanced mobile applications.

Full Stack Developer Course Banner