How can I make a div disappear when clicked outside of it using JavaScript?

I want to create a scenario where a "form" is only visible after clicking on another "button" under the following conditions:

  • The "form" will only appear if the user clicks on the "button".
  • If the user clicks anywhere outside of the form or clicks the button again, the form should become hidden.

/* JAVASCRIPT */
const outer = document.getElementById('outer');
const inner = document.getElementById('inner')
outer.onclick = function() {
  if (inner.style.visibility == 'visible') {
    document.getElementById('inner').style.visibility = 'hidden';
  } else {
    document.getElementById('inner').style.visibility = 'visible';
  }
}
const ignoreClickOnMeElement = document.getElementById('inner');
document.addEventListener('click', function(event) {
  const isClickInsideElement = ignoreClickOnMeElement.contains(event.target);
  if (!isClickInsideElement) {
    // when uncommenting the line below everything stop working, rather then just closing if I click outside this div
    /*    document.getElementById('inner').style.visibility='hidden';*/
  }
});
/* CSS */

* {
  border: thin solid black;
}
<!-- HTML -->

<body>
  <div class="outer" id="outer">
    <button>Visible</button>
  </div>
  <div class="inner" id="inner" style="visibility: hidden;">
    <form id="form">
      <input type="number">
      <input type="number">
    </form>
  </div>
</body>

Answer №1

By using a delegated event listener attached to a higher node, for example the document body as shown here, you can identify which elements have been clicked based on the event target.

let form=document.getElementById('form');
let bttn=document.querySelector('div.outer button');

document.body.addEventListener('click',e=>{

  e.preventDefault();
  e.stopPropagation();

  if( ( e.target==bttn && form.parentNode.style.visibility!=='visible' ) || e.target==form || e.target.parentNode==form ){
    form.parentNode.style.visibility='visible'
  }else{
    form.parentNode.style.visibility='hidden'
  }
  

})
* {
    border: thin solid black;
}
form{
  height:100px;width:80%;background:pink
}
.inner{
  height:200px;width:100%;
}
.outer{
  width:100%;height:100px;
}
<div class="outer" id="outer">
  <button>Visible</button>
</div>
<div class="inner" id="inner" style="visibility: hidden;">
  <form id="form">
    <input type="number>
    <input type="number>
  </form>
</div>

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

Updating entire DOM in javascript

Implementing undo-redo functionality in my project has proven to be quite complex, as every change affects numerous elements. I believe that saving and restoring the entire page may be the most effective solution. However, I have encountered issues with mi ...

The page is reloading after the PageMethod has been utilized

I am looking to implement search functionality in my popup window. The popup includes a textbox, a button, and a grid to display the search results. This is how the popup appears: Upon clicking the search button, I have a JavaScript function set up to c ...

What is preventing the navbar from appearing on top of everything else?

I'm currently facing an issue with my website where the navbar at the top is not displaying above all other content as expected. Despite trying various approaches such as adjusting the z-index and setting absolute positioning, the navbar still remains ...

Order Typescript by Segment / Category

Suppose we start with this original array of objects: {vendor:"vendor1", item:"item1", price:1100, rank:0}, {vendor:"vendor1", item:"item2",price:3200, rank:0}, {vendor:"vendor1", item:"item3", price:1100, rank:0}, {vendor:"vendor2", item:"item1", price: ...

Adding additional filters to an already existing filter function while querying Azure Mobile Services

In my Angular Web App, I am utilizing the Azure Mobile Services library for JavaScript. The documentation states that there are two methods to filter returned data: passing a JSON object or using a filter function for more complex filtering. Since I need t ...

Check out the performance metrics of Preact post-render

I'm currently working on monitoring the time it takes in preact to update a component and render it. Below is the code snippet I am using : handleKeyPress(event) { renderingTime = Date.now() ... } componentDidUpdate() { if (renderingTim ...

Is it feasible for Javascript to trigger a callback or signal with Selenium?

Imagine using Selenium on a web page that utilizes an AJAX request to dynamically update content within a specific #content element. The #content element always has exactly five children, each without any classes, ids, or unique identifiers. Periodically, ...

Managing the Loading Sequence of CSS Files in Nuxt and Vuetify

I am facing an issue in my Nuxt/Vuetify application where I cannot seem to load my custom CSS file after Vuetify's CSS. Despite attempting to change the order in the CSS array like so: css: [ '~/assets/style/main.scss', '~/asse ...

Using Angular 4 Component to Invoke JavaScript/jQuery Code From an External File

I have written a jQuery code that is executed at ngAfterViewInit(). //myComponent.ts ngAfterViewInit() { $(function () { $('#myElement').click(function (e) { //the code works fine here }); } However, I want t ...

Displaying images in a React app using Node.js

I receive the image from the user as formdata Here is how I structured the Schema for the image The Image has been successfully stored in Monogodb This is my process of fetching image information using Axios I implement code for rendering the image on the ...

ASP.net and javascript work in unison to seamlessly trigger the automatic opening of

I want to incorporate a lightbox that will automatically open when visitors land on my homepage. I'm looking for something akin to the functionality found at . Any suggestions on how I can achieve this? ...

When a model.find is passed as an argument to be invoked, it results in an error

After working with ExpressJS for a while, I decided to explore using Mongoose alongside it. In the callback of my queries where I handle errors like this: function( error, data ) {...} , I found myself repeating code. To streamline this process, I created ...

Solving an issue with conflicting Javascript code

I'm experiencing an issue with JavaScript. I have implemented two scripts for a select element on my website. One script handles submitting it without a submit button, and the other script is responsible for custom styling the select. Here are the two ...

Pass information between two forms using the Post method and Ajax communication

For my project, I attempted to retrieve data using the POST method in the processing file but encountered difficulties. I need to be able to receive the data through the POST method and display it on process.php. It's worth noting that my inputs are n ...

Retrieving the dimensions of a concealed element

I am facing a minor issue and I need some assistance in figuring out what I might be missing here. Here is my html code: <div class="drop-down-menu"> <div class="innerdrop-down-menu"> <div id="first-tab-cont"> <ul id=" ...

Steps for launching an application through a hyperlink to appear on the foreground rather than the background

For my project, I am utilizing "a href" to open a windows application. <a href={`enter app here`}> //Similar concept as mailto The issue I am facing is that it opens the application in the background rather than bringing it to the foreground. Esse ...

Employing the findOne method repeatedly in a loop can significantly slow down operations in Node.js

Currently, I am working on a project using Node.js in conjunction with MongoDB, specifically utilizing Monk for database access. The code snippet I have is as follows: console.time("start"); collection.findOne({name: "jason"}, function(err, document) { ...

Navigate through the JSON object and generate all possible combinations of nested elements

Here is a JSON object that I need to iterate through in order to generate all possible nested group names: { "groups": [ { "group": "group1", "childrens": [ { "group": "group1_1", ...

Unable to store the user's input information in the database

I've been attempting to incorporate an "add" button feature that saves/adds/inserts data into my table. I have inputted some text in the form of tags (input type), but unfortunately, it doesn't seem to be functioning properly. Despite conducting ...

The class name remains unchanged despite the change in value

I am currently working on a webpage that features two interactive tabs. The goal is to have one tab highlighted as "active" while the other remains inactive when clicked, and then switch roles when the other tab is selected. Below is the code snippet I ha ...