Hide a div when the user clicks outside of it using jQuery

Let's see how can we hide some element, say div, when the user clicks outside of it using jQuery?
Submitted by Pratishtha Saxena, on August 25, 2022

Hiding or showing up elements on clicks is very important to understand when making the webpages.

Now, let's understand what is hiding elements when clicking outside means. Whenever the user clicks somewhere else and not where the div element is present, then the element must get hidden. Here we'll be taking an example of a div element, but this can be performed on any DOM element.

For this, jQuery's closest() method will be useful. Majorly it helps in returning the closest, i.e., the first ancestor of the element specified.

Syntax:

$(selector).closest('filter');

But the question arises that how will it be able to return whether the click was inside or outside the "div element. So, along with this method, we'll be specifying the length property equals zero. If the ancestor returned by the "closest() method has a length equal to zero, then it is outside the element selected.

This is clearer when used in an example.

Example to hide a div when the user clicks outside of it using jQuery

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    <title>Document</title>
  </head>
  
  <body>
    <h2 data-name="John">Select Elements By Data Attributes</h2>
    <div id="myDiv" data-name="Tom" data-age="20">Welcome to Include Help !!</div>
    <p data-name="Harry">jQuery Tutorial</p>
    <button type="button" id="button1">Click Here</button>
  </body>
  
  <script type="text/javascript">
    $(document).ready(function(){
        $('#button1').on('click',function(){
            var name = $('[data-name = "Tom"]').data('name');
            alert(name);
    
        });
    });
  </script>
</html>

Output:

Example 1: Hide a div when the user clicks outside

After clicking outside of the DIV

Example 2: Hide a div when the user clicks outside






Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.