how-to-hide-a-div-when-the-user-clicks-outside-of-it-using-jquery?

While navigating the webpage, you may encounter dropdown menus, modals, or tooltips that vanish when a user clicks outside of them. This is a frequent functionality in website development. In this article, we will explore various techniques for concealing a div using jQuery, complete with demonstrations.

Contents:

Techniques to Conceal a Div when the User Clicks Outside It Using jQuery

You can employ functions such as click(), closest(), is(), and has() collectively to hide a div when the user clicks outside of it using jQuery. Let’s delve into these functions below.

Technique 1: Utilizing Closest() Method

Upon clicking anywhere on the page, the script verifies if the click originated within the #myDiv. If the click occurs outside it, the div will be concealed. Conversely, clicking within the div keeps it visible, as the click event does not reach other parts of the page.

Sample Code:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Conceal 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">Display Div</button>
    <div id="myDiv" style="display: none;">
        Click outside of this area to conceal it.
    </div>

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

Result:

Utilizing Closest() Method Output

Clarification: When a click occurs on the page, the code searches for the closest ancestor matching #myDiv or #showDiv using $(event.target).closest(“#myDiv, #showDiv”). If a match isn’t found, myDiv will be hidden.

Technique 2: Utilizing click() Method

The jQuery click() method enables you to establish a function that activates when a user clicks on an element. This method can be employed to determine if a user clicks anywhere on the page or solely inside a specified element. It’s ideal for concealing a <div> when a user clicks externally.

Sample Code:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Conceal Div on External Click</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">Display Div</button>
    <div id="myDiv" style="display: none;">
        Click outside of this section to conceal it.
    </div>

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

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

Result:

Utilizing click() Method Output

Clarification: The click can be sensed on the document with this method. The $(event.target).is(“#myDiv, #showDiv”) function checks whether the click occurs on either of the divs. If the clicked element is outside, #myDiv will be concealed.

Technique 3: Utilizing is() and has() Method

The is() and has() methods are utilized for filtering and validating elements according to specific criteria. You can combine these methods to ascertain whether a click is inside or outside a target element.

Sample Code:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Conceal Div on External Click</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:```html
 100px auto;
      padding: 20px;
      text-align: center;
      box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
    }
    /* Design for a message external to 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 Conceal It</h3>
    <p>This div will be concealed when you click outside of it.</p>
  </div>
  <div id="outsideMessage">
    <p>To hide the blue box above, click outside it.</p>
  </div>
  <script>
    $(document).click(function(event) {
      // Verify if the click occurs outside the #targetDiv
      if (!$(event.target).closest('#targetDiv').length) {
        // Hide the div if the click occurs outside
        $('#targetDiv').hide();
      }
    });

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

Output:

Using is() and has() Method Output

Explanation: The target div is visible upon loading the page. The concealment action is not activated when clicking inside the div, while clicking outside causes it to be hidden.

Conclusion

The methods outlined above are highly efficient for concealing a div when clicks occur outside. Functions such as click(), closest(), is(), and has() can be employed to effortlessly hide a div when a user clicks externally using jQuery. This functionality can be advantageous for creating dropdown menus, modals, and various dynamic components on your webpage.

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

The article How to Hide a Div When the User Clicks Outside of it using jQuery? was first published on Intellipaat Blog.

“`


Leave a Reply

Your email address will not be published. Required fields are marked *

Share This