Issue with Event.target not functioning properly when clicking outside the div to close it

I am facing an issue with my main div and sub div, which is referred to as a form because it is enclosed within the main div. I am trying to close the form when clicking outside of the main div, but unfortunately, this functionality is not working as expected. Can someone assist me in resolving this problem?

var btn = document.getElementById('opener');
var box = document.getElementById('abc');
var form = document.getElementById('def');

btn.onclick = function(){
box.style.display = "block";
}

//The code below should close the form when clicked outside of the div.
window.onclick = function(event){
if(event.target == box){
  form.style.display = "none";
  }
}
#abc{
  display: none;
  background-color: #F44336;
}
<button id = "opener">
  Open
  </button>
  <div id = "abc">
<!-- Login Authentication -->
<div id = "def">
<div>
<p>Welcome</p>
</div>
<br />
<div class = "login-auth" id = "cool">
<form method="POST">
<label>Email or Username:</label>
<input type = "text">
<br />
<label>Password:</label>
<input type = "password">
<br /><br />
<input type="submit" value="Login">
</form>
</div>
</div>
</div>

You can view the JSFiddle for this code here.

Answer №1

Your code is functioning correctly, however, to achieve the desired effect, you should prevent the click event from propagating by using e.stopPropagation() on both the button and the popup window. Take a look at my example below:

#def{
  border:1px solid black;
}
#abc{
  padding:40px;
}

var btn = document.getElementById('opener');
var box = document.getElementById('abc');
var form = document.getElementById('def');

btn.onclick = function(e) {
  e.stopPropagation();
  box.style.display = "block";
}
box.onclick = function(e) {
  e.stopPropagation();
}

// This part of the code aims to close the form when clicking outside the div, but it's not working as expected
window.onclick = function(event) {
    box.style.display = "none";
}
#abc {
  display: none;
  background-color: #F44336;
}

#def {
  border: 1px solid black;
}

#abc {
  padding: 40px;
}
<button id="opener">
  Open
</button>
<div id="abc">
  <!-- Login Authentication -->
  <div id="def">
    <div>
      <p>Welcome</p>
    </div>
    <br />
    <div class="login-auth" id="cool">
      <form method="POST">
        <label>Email or Username:</label>
        <input type="text">
        <br />
        <label>Password:</label>
        <input type="password">
        <br />
        <br />
        <input type="submit" value="Login">
      </form>
    </div>
  </div>
</div>

Answer №2

Although this may not be directly related to your query, have you thought about implementing a toggle button instead? It's simpler to execute and provides a more intuitive user experience.

var btn = document.getElementById('opener');
var box = document.getElementById('abc');
var form = document.getElementById('def');

btn.onclick = function(e){
    
    
    if(e.target.innerHTML === 'Open'){
     box.style.display = "block";
     e.target.innerHTML = "Close"
    }else{
      box.style.display = "none";
     e.target.innerHTML = "Open"
    }

}

// This section is supposed to close the form when clicking outside of the div, but it doesn't work as intended.
window.onclick = function(event){
if(event.target == box){
  form.style.display = "none";
  }
}
#abc{
  display: none;
  background-color: #F44336;
}
<button id = "opener">
  Open
  </button>
  <div id = "abc">
<!-- Login Authentication -->
<div id = "def">
<div>
<p>Welcome</p>
</div>
<br />
<div class = "login-auth" id = "cool">
<form method="POST">
<label>Email or Username:</label>
<input type = "text">
<br />
<label>Password:</label>
<input type = "password">
<br /><br />
<input type="submit" value="Login">
</form>
</div>
</div>
</div>

Answer №3

The function window.onclick may experience compatibility issues with specific browser types. It is recommended to use document.onclick as an alternative solution.

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

What is the best way to clean HTML in a React application?

I am trying to showcase HTML content on the React front end. Here is the input I have: <p>Hello/<p> Aadafsf <h1>H1 in hello</h1> This content was written using CKEditor from the Admin side. This is how it appears on the React fro ...

When inserting <img>, unwanted gaps appear between div elements

When I have <img> in the child divs, there is some space between them and a blue stripe appears under the image. How do I make them stack perfectly without any gaps? I am new to HTML and CSS and trying to learn for marketing purposes. Any help or ad ...

Avoiding the Creation of Duplicate IDs in MongoDB

Within my backend using Node and MongoDB, I have a model that makes a reference to a collection of payers. Here is an example of how it is implemented: clients: [{ id: { type: mongoose.Schema.Types.ObjectId, ref: 'clients' } }], Currently, this ...

What is the most efficient way to refresh a React component when a global variable is updated?

I've built a React component called GameData that displays details of a soccer game when it is clicked on in a table. The information in the table is updated by another component, which changes a global variable that GameData relies on to show data. S ...

React component failing to display CSS transitions

The task at hand requires the component to meet the following criteria: Items in a list should be displayed one at a time. There should be two buttons, Prev and Next, to reveal the previous or next item in the list. Clicking the Back/Next button should tr ...

What is the correct method of implementing the "OnChange" event to a WooCommerce select element?

My task is to include the onchange="myFunction()" in the select menu below. However, because the select menu is part of woocommerce, I want to ensure that the onchange="myFunction()" remains intact even after updating my theme. How can I achieve this goal ...

Is it possible to display CKEditor5 toolbar buttons in a separate row rather than the primary row?

https://i.stack.imgur.com/Tyfqb.png I successfully integrated CKEditor5 into my create react app directly from the source code. However, I am facing an issue where the overflowed buttons in the toolbar are being displayed in a separate menu item instead o ...

How can I effectively transfer parameters to the onSuccess callback function?

In my react-admin project, I'm utilizing an Edit component and I wish to trigger a function upon successful completion. <Edit onSuccess= {onSuccess } {...props}> // properties </Edit> Here's the TypeScript code for the onSuccess fun ...

Include an additional Div tag in the existing row

I've been attempting to include an additional div, but it consistently appears as the second row.. I want all of them to be on the same row and aligned with each other. Here is the HTML code: <div class="content-grids"> <div clas ...

emailProtected pre-publish: Running `python build.py && webpack` command

i am currently using scratch-blocks through the Linux terminal I have encountered a problem which involves running the following command: python build.py && webpack [email protected] prepublish: python build.py && webpack Can anyon ...

Having trouble retrieving an object from an event handler in ReactJS

const question = { quest : "What is my age?", answers : [16,15,21,30], correct : 21, } validateAnswer(){ let usersResponse = document.getElementById('ans-1').textContent; let response = this.question.correct; if(usersResp ...

Styling Radio Buttons and Links in Horizontal Layout Using Bootstrap

Encountering an issue in Bootstrap while attempting to incorporate custom radio buttons and a hyperlink in the same row. It seems that either the hyperlink functions OR the data-toggle feature for radio buttons works, but not both simultaneously, especiall ...

AngularJS tree grid component with customizable cell templates

I have been utilizing the tree-grid component in AngularJS from this link: Here is an example of it on Plunker: http://plnkr.co/edit/CQwY0sNh3jcLLc0vMP5D?p=preview In comparison to ng-grid, I am unable to define cellTemplate, but I do require the abilit ...

Guide on retrieving the AWS IAM user in string/json format using STS GetCallerIdentity Caller JS/TS

I am attempting to retrieve the AWS IAM Arn user using the STS GetCallerIdentity API provided by Amazon. The following code successfully logs the correct data in the console. Nevertheless, I am encountering difficulty returning the data as a string or JSON ...

Designing a div that fills the entire height and 75% of the body's width

As a newbie to HTML/CSS, I'm struggling with implementing what I described in the title. It was functioning properly earlier, but now it seems like I made a mistake somewhere and it's no longer working. My code is quite lengthy, but the remainin ...

What is the best way to send the current ID for data deletion in React?

Here is my current code snippet: var html = []; for (var i = 0, len = this.props.tables.length; i < len; i++) { var id = this.props.tables[i]._id;//._str; html.push( <div key={id} className="col-xs-6 col-md-3"> ...

Incorporating HTML 5 data attributes into the DOM using jQuery

I'm attempting to insert an HTML 5 data attribute into the DOM. According to the jQuery site, the format for data attributes is as follows: $('.pane-field-related-pages ul').data("role") === "listview"; However, it doesn't appear to b ...

Guide to sending client-to-client notifications in Angular/Ionic with Firebase Cloud Messaging

I am looking to implement client-client push notifications (not server-to-client). My goal is to send a notification when one user messages another. Is this feasible? How can I achieve this using the structure in the Firebase real-time database? Here is a ...

Generate a bill based on items in a virtual shopping cart

I am having trouble with formatting the output of a shopping cart to an invoice. The data is displaying, but it's not showing up correctly. https://i.sstatic.net/eCKs3.jpg Here's the code snippet: <table class="table table-striped"> ...

Customizing Your WooCommerce Storefront: Tips for Enhancing Your Product Catalog and Minimizing White Space

Lately, I've been working on enabling a product filter in the left sidebar of my Woocommerce theme. However, I have noticed that the layout is not quite how I would like it to be. Take a look at this image that shows the changes I am aiming for. Cur ...