JavaScript Magic: Hide Div when Clicking Away

I need a solution where clicking outside of the My DIV with the ID Container_ID will hide all elements within the Container by setting their style to display: none;. Currently, the JavaScript code I am using partially achieves this functionality, but it also hides the My DIV when clicking inside any part of the Container_ID. This is not the intended behavior, especially when interacting with elements like Controls_CLASS, ul, li, or Checkbox_CLASS within the Container_ID itself. These elements should not trigger the hiding of the entire Container_ID when clicked, as they are part of the container.

Is there a way to improve this functionality?

JavaScript (source: https://codepen.io/marizawi/pen/YgaaMp)

window.addEventListener('mouseup', function(event) {
  var cont = document.getElementById('Container_ID');
  if (event.target != cont && event.target.parentNode != cont) {
    cont.style.display = 'none';
  }
});
div.Container_CLASS {
  width: 50%;
  height: 350px;
  margin-top: 4px;
  margin-left: 4px;
  display: block;
  position: absolute;
  overflow-y: scroll;
}
<div class="Container_CLASS" id="Container_ID">
  <div class="Controls_CLASS"><a href="#">Select All</a>|<a href="#">Reset</a></div>
  <ul>
    <li><input type="checkbox" name="cars[]" class="Checkbox_CLASS" value="BMW" />BMW</li>
    <li><input type="checkbox" name="cars[]" class="Checkbox_CLASS" value="Mercedes" />Mercedes</li>
    <li><input type="checkbox" name="cars[]" class="Checkbox_CLASS" value="Volvo" />Volvo</li>
  </ul>
</div>

Answer №1

To implement this feature, the closest method is used to verify if a click occurred outside of a specified div.

closest

An element's ancestors include its parent, the parent's parent, and so forth, forming a series of parents leading to the top.

The elem.closest(css) method searches for the closest ancestor that matches the CSS selector. The element elem itself is also part of the search.

In essence, the closest method moves up from the element and examines each parent. When a match is found, the search ends, and the ancestor is returned.

If a div has an id:

 window.addEventListener('mouseup',function(event){
        var pol = document.getElementById('pol');
        if(!(event.target.closest("#pol"))){
            pol.style.display = 'none';
        }
  });  
h2{margin:0 0 10px}
#pol{
    width:400px;
    height:300px;
    background:#999;
    text-align:center;
    display:none;
    margin-top:0;
    margin:10px;
}
<h2>Click outside div will be hide. Click Button div will be display</h2>
<button onClick="document.getElementById('pol').style.display='block'">Show</button>
<div id="pol">
I am Tanmoy Biswas
  <p>ksjdhfksjdhfkjshdfkjsdfsf</p>
<div class="Controls_CLASS"><a href="#">Select All</a>|<a href="#">Reset</a></div>
  <ul>
    <li><input type="checkbox" name="cars[]" class="Checkbox_CLASS" value="BMW" />BMW</li>
    <li><input type="checkbox" name="cars[]" class="Checkbox_CLASS" value="Mercedes" />Mercedes</li>
    <li><input type="checkbox" name="cars[]" class="Checkbox_CLASS" value="Volvo" />Volvo</li>
  </ul>
</div>

If a div has a class:

 

    window.addEventListener("mouseup", function (event) {
  let pol = document.querySelectorAll(".pol");
  pol.forEach((myDiv) => {
    if (!(event.target.closest(".pol"))) {
      myDiv.style.display = "none";
    }
  });
});
h2{margin:0 0 10px}
.pol{
    width:400px;
    height:300px;
    background:#999;
    text-align:center;
    display:none;
    margin-top:0;
    margin:10px;
}
<h2>Click outside div will be hide. Click Button div will be display</h2>
<button onClick="document.getElementById('a').style.display='block'">Show</button>
<div id="a" class="pol">
I am Tanmoy Biswas
  <p>ksjdhfksjdhfkjshdfkjsdfsf</p>
<div class="Controls_CLASS"><a href="#">Select All</a>|<a href="#">Reset</a></div>
  <ul>
    <li><input type="checkbox" name="cars[]" class="Checkbox_CLASS" value="BMW" />BMW</li>
    <li><input type="checkbox" name="cars[]" class="Checkbox_CLASS" value="Mercedes" />Mercedes</li>
    <li><input type="checkbox" name="cars[]" class="Checkbox_CLASS" value="Volvo" />Volvo</li>
  </ul>
</div>


<h2>Click outside div will be hide. Click Button div will be display</h2>
<button onClick="document.getElementById('b').style.display='block'">Show</button>
<div id="b" class="pol">
I am Tanmoy Biswas
  <p>ksjdhfksjdhfkjshdfkjsdfsf</p>
<div class="Controls_CLASS"><a href="#">Select All</a>|<a href="#">Reset</a></div>
  <ul>
    <li><input type="checkbox" name="cars[]" class="Checkbox_CLASS" value="BMW" />BMW</li>
    <li><input type="checkbox" name="cars[]" class="Checkbox_CLASS" value="Mercedes" />Mercedes</li>
    <li><input type="checkbox" name="cars[]" class="Checkbox_CLASS" value="Volvo" />Volvo</li>
  </ul>
</div>

Answer №2

Here is my approach:

To determine whether the clicked element (event.target) is within the container or if it is the element triggering the container display, you can use the following code:

const theDiv = document.getElementById('theDiv');
const theButton = document.getElementById('theButton');

document.addEventListener('click', function(event) {
  if (theDiv.contains(event.target) || event.target.id === 'theButton') return;
  theDiv.hidden = true;
})
div {
  background-color: red;
  height: 400px;
  width: 400px;
}
<button type="button" onclick="this.nextElementSibling.hidden=false" id="theButton">Show</button>
<div hidden id="theDiv">
  <button>clicking here won't close</button>
</div>

For your specific case:

const container = document.getElementById('Container_ID');

document.addEventListener('click', function(event) {
  if (container.contains(event.target)) return;
  container.hidden = true;
})
div.Container_CLASS {
  border: 1px solid red;
  width: 50%;
  height: 350px;
  margin-top: 4px;
  margin-left: 4px;
  position: absolute;
  overflow-y: scroll;
}
<div class="Container_CLASS" id="Container_ID">
  <div class="Controls_CLASS"><a href="javascript:void(0)">Select All</a>|<a href="javascript:void(0)">Reset</a></div>
  <ul>
    <li><input type="checkbox" name="cars[]" class="Checkbox_CLASS" value="BMW" />BMW</li>
    <li><input type="checkbox" name="cars[]" class="Checkbox_CLASS" value="Mercedes" />Mercedes</li>
    <li><input type="checkbox" name="cars[]" class="Checkbox_CLASS" value="Volvo" />Volvo</li>
  </ul>
</div>

Answer №3

Consider these various choices for implementation

In my opinion, the optimal solution is utilizing the mouse leave event

Triggered by Mouse Leave

document.getElementById("Box_ID").addEventListener('mouseleave',function(event){
    document.getElementById("Box_ID").style.display = "none";
});

Triggered by Focus Out

document.getElementById("Box_ID").addEventListener('focusout',function(event){
    document.getElementById("Box_ID").style.display = "none";
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Troubleshooting IE compatibility issues with jQuery .hide() method

I am encountering a curious issue with hiding span elements using CSS (display: none;). Upon page load, I expect the first span element to be displayed, which it does in all browsers except IE7. This anomaly has left me perplexed as there is no unusual cod ...

What should I do when using _.extend() in express - override or add in fields?

When an object is extended by another object with values set for some of the extended fields, will it be rewritten or will the new values be added? For example: const PATCH_REQUEST_SCHEMA = { 'type': 'object', 'title' ...

Display the table upon completion of the form submission

I am trying to create a form where the table #mytable is only displayed after the form has been submitted. If nothing is entered in the form, the table should remain hidden. Any suggestions on how I can achieve this? <form action="" id="myform" method ...

Tips for concealing overlay when the cursor hovers

Can anyone help me with a code issue I'm having? I want to hide an overlay after mouse hover, but currently it remains active until I remove the mouse from the image. Here is the code: .upper {position: absolute; top: 50%; bottom: 0; left: 50%; tra ...

The initial Ajax request returned an empty data string, but upon retrying, the correct data

Let's address the current situation Previously, I had a free domain that was unexpectedly closed by the web admins without any explanation. Everything functioned perfectly on that domain, but after opening a new one on a different site, I started enc ...

What specific files from the Kendo core are required for utilizing Mobile and Angular functionalities?

After browsing through similar questions, I couldn't find a solution. Currently, I am experimenting with Kendo (open source core for now) in a Visual Studio Cordova project. Initially, disregarding Cordova, I am focusing on setting up a basic view wit ...

Create a path on the Google Map that follows the designated route

I am looking for a solution similar to one found here: Sample However, I have been unable to find a suitable solution anywhere. The main issue is being able to follow the route in order to draw a line between two points. Can anyone provide guidance on ho ...

Infinite loop readiness with JQuery

My current project involves preloading images and seamlessly fading them in once they are fully loaded using JQuery. To achieve this, I attempted to create an invisible image tag where the images would load before setting the source back to the original im ...

Using the Proper 'this' Reference Without Repeating 'this' in Nested Functions

I am facing an issue in my class where I have multiple methods and properties. One of these methods contains a setTimeout() function as follows: function myClass() { this.some_property = "test"; this.PrintOnTimeout = function() { // I thou ...

Issue with Chrome Browser Border Radius Bug when applied to element with Display: Table

I'm facing an issue with border radius in the Chrome browser. When applying a border-radius to an element styled with dashed border-style and display:table, the background-color exceeds the limit of the border. Here's how it appears in Chrome: ...

Customize the font color in Material UI to make it uniquely yours

How can I customize the default Text Color in my Material UI Theme? Using primary, secondary, and error settings are effective const styles = { a: 'red', b: 'green', ... }; createMuiTheme({ palette: { primary: { ...

There was an issue with the Google Maps embed API that resulted in an error with interpolation

My goal is to utilize the Google Maps API in order to showcase a map using data from a JSON file. However, whenever I attempt to incorporate the JSON data, an error message 'Error: [$interpolate:noconcat] Error while interpolating' pops up. < ...

Leveraging Material-UI: Utilize props in useStyles method while employing Array.map()

After delving into the world of passing props to makeStyles in Material-UI, I stumbled upon this insightful answer. The solution presented involves passing props as a variable, which is quite useful. However, my aspiration is to extend this functionality t ...

The callback function is unable to access this within the $.post method

Hey there, I'm new to JavaScript/jQuery and I could use some help. I have an object prototype called Page that contains an array and a function for making an AJAX POST request and processing the response. Here's a snippet of the code: function P ...

Node.js reads and writes a JSON file, encountering issues with another application in the process

I'm currently facing an issue with my node.js server (express.js) and a json file used for reading and writing data through a simple API. Interestingly, when the node.js server is stopped, another application can add data to the json file without any ...

Handling TextChanged Event of a TextBox in ASP.NET using C#

I'm currently designing a POS screen that allows barcode scanning directly into a textbox. I want to implement a code behind procedure that adds the barcode-related data to the grid as soon as the textbox text changes. This is how my textbox looks: &l ...

Creating a function that writes to a file by utilizing the data input from

After running the provided code snippet, it successfully works in a standalone project. However, I am interested in making modifications to replace the variable "sample_text" with an output that is displayed in the terminal instead of being hardcoded int ...

What is the best way to create a list from a matrix using JavaScript?

I have an array structured as follows: const input_array= [ ["red", "green"], ["small", "medium"], ["x", "y", "z"] //... can have any number of rows added dynamically ...

Receiving NaN in javascript when attempting to calculate the sum using a text input field

I am trying to calculate the total value by adding a fixed price with another value entered in a text input field. Here is the HTML code snippet: <%= f.text_field :hoursclass, id:"txt_hours" %> And here is the JS code snippet: $(function() { va ...

Off Canvas left navigation menu using Bootstrap

I am working on creating a responsive layout for a webpage using Bootstrap. On larger displays, such as desktop resolutions, I want the webpage to show the header and left navigation as normal. However, when the site is resized to that of tablets or mobile ...