Close the overlay by clicking outside of it

I'm working on creating a unique pop-up window that appears when a customer adds a product to their cart. The design features red and green background divs with a darker overlay (#overlay-daddy) and a white child div (#overlay).

My issue arises from using JS with an event listener on #overlay-daddy, which is intended to hide the display property. However, it also triggers when clicking on #overlay itself. Any help would be appreciated!

Below is the code snippet:

#overlay-daddy {
  position: absolute;
  z-index: 1;
  background-color: rgba(0, 0, 0, 0.6);
  width: 100%;
  height: 100%;
  top: 0;
  left: 0;
}

#overlay {
  position: absolute;
  z-index: 2;
  top: 30%;
  left: 20%;
  width: 60%;
  height: 40%;
  background-color: #fff;
}
<html lang="fr">
<head>
  <meta charset="utf-8">
  <link rel="stylesheet" href="/css/batiprox_common.css">
</head>
<body>
  <div style="height: 50%; background-color: red"></div>
  <div style="height: 50%; background-color: green"></div>
  <div id="overlay-daddy">
    <div id="overlay">
    </div>
  </div>
  <script type="text/javascript">
    var dad = document.getElementById('overlay-daddy');
    //dad.addEventListener("click", function() { this.style.display = "none";});
    dad.addEventListener("click", function() { alert(this); });
  </script>
</body>
</html>

Answer №1

To prevent the event from propagating further, remember to include e.eventPropagation() within the event listener for the overlay.

var dad = document.getElementById('overlay-daddy');
var overlay = document.getElementById('overlay');

overlay.addEventListener("click", function(e) {
  e.stopPropagation();
});

dad.addEventListener("click", function() {
  alert(this);
});
#overlay-daddy {
  position: absolute;
  z-index: 1;
  background-color: rgba(0, 0, 0, 0.6);
  width: 100%;
  height: 100%;
  top: 0;
  left: 0;
}

#overlay {
  position: absolute;
  z-index: 2;
  top: 30%;
  left: 20%;
  width: 60%;
  height: 40%;
  background-color: #fff;
}
<div style="height: 50%; background-color: red"></div>
<div style="height: 50%; background-color: green"></div>
<div id="overlay-daddy">
  <div id="overlay">
  </div>
</div>

Answer №2

Ensure a click handler is registered on #overlay where the default behavior is prevented;

One way to do this is:

document.getElementById('overlay').addEventListener('click', function(e) {
   e.preventDefault();
   e.cancelBubble();
   e.stopPropagation();
}, true);

It's worth noting that you may not need all three calls, but my memory is fuzzy on which ones are essential.

Answer №3

To prevent the click event from triggering in the children of an overlay, you can check if the clicked element is the overlay itself and not one of its children by using if(event.target===this):

#overlay-parent {
  position: absolute;
  z-index: 1;
  background-color: rgba(0, 0, 0, 0.6);
  width: 100%;
  height: 100%;
  top: 0;
  left: 0;
}

#overlay {
  position: absolute;
  z-index: 2;
  top: 30%;
  left: 20%;
  width: 60%;
  height: 40%;
  background-color: #fff;
}
<html lang="fr">
<head>
  <meta charset="utf-8">
  <link rel="stylesheet" href="/css/custom_styles.css">
</head>
<body>
  <div style="height: 50%; background-color: red"></div>
  <div style="height: 50%; background-color: green"></div>
  <div id="overlay-parent">
    <div id="overlay">
    </div>
  </div>
  <script type="text/javascript">
    var parent = document.getElementById('overlay-parent');
    
   //parent.addEventListener("click", function() { this.style.display = "none";});
    
    parent.addEventListener("click", function(event) {
      if(event.target===this) alert(this);
    });
  </script>
</body>
</html>

Answer №4

The 'overlay' element is currently causing the 'click' event to propagate to its parent. To prevent this, you can incorporate the use of event.stopPropogation on your 'overlay' element.

To make this adjustment, consider updating your overlay element as shown below.

<div id="overlay" onclick="event.stopPropagation();">
</div>

Answer №5

It appears that your code is missing the bottom and right properties in #overlay-daddy

#overlay-daddy {
  position: absolute;
  z-index: 3; // edited
  background-color: rgba(0, 0, 0, 0.6);
  width: 100%;
  height: 100%;
  top: 0;
  left: 0;
  bottom: 0; // added bottom
  right: 0; // added right
}

Therefore, in order to click within #overlay-daddy, you must ensure its z-index is higher than #overlay

I hope this information proves useful to you.

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

Can you explain the meaning behind the code Array.remove = function() {...}?

I encountered this code snippet that has left me puzzled: Array.remove = function(array, from, to) { var rest = array.slice((to || from) + 1 || array.length); array.length = from < 0 ? array.length + from : from; return array.push.apply(arr ...

Is there a correct way to properly duplicate a JSON array in Redux?

As a newcomer to Redux, I found the concepts somewhat confusing at first. For instance, imagine that there is an array in the redux state. const state = [ {show: false, id : '1'}, {show: false, id : '2'}, {show: false, id : &apo ...

The Angular Google Maps Directive zooms in too much after the "place_changed" event has fired

Currently, I am developing a store locator app for DHL accessible at storefinder.hashfff.com/app/index.html For this project, I decided to utilize the angular-google-maps library for its features. However, in hindsight, working directly with the Google Ma ...

How can Node.js developers properly utilize PM2 for their projects?

I'm currently contemplating a switch from forever to PM2 as a way to ensure my node application stays up and running. I find myself puzzled by the various recommended methods for initiating a process: $ pm2 start app.js -i 4 # Daemonize pm2 and Star ...

Troubles encountered with adapting apexcharts size within a react environment

As a novice front-end coder transitioning from a data analyst background, I am currently facing an issue with integrating an ApexChart visual into a flexbox element. The visual appears fine at a resolution of 2560x1440 pixels. However, upon further resizin ...

Verify if the SaveAs dialog box is displayed

Can javascript/jquery be used to detect the appearance of a SaveAs dialogue box? I need to know if it's displayed in order to remove a loading gif. Any ideas? ...

Tips for handling Promise.all and waiting for all promises to resolve in an async function in Express JS

I'm relatively new to JavaScript and especially asynchronous programming. My current project involves creating an Express+React application that shows a GitHub user's information, including a few repositories with the latest 5 commits for each. ...

Binding iframes in Angular 6

Is there a way to display iframe code stored in a variable within a div? Here's the HTML code: <div class="top-image" [innerHTML]="yt"></div> And here's the TypeScript code: yt = '<iframe class="w-100" src="https://www.you ...

Changing the `$location.path` updates the URL without triggering a redirect

When I try to redirect to another page by clicking a button or a link, the URL changes but the redirection doesn't happen. I have to manually refresh the page with the new URL. I'm not sure if the issue lies in the module or the controller. loca ...

Ways to transform a PHP function into one that can be invoked using Ajax

In my current project, I’m facing an issue where I need to call multiple PHP functions that output HTML using Ajax. Instead of directly trying to call a PHP function with Javascript, I believe application routing can help the frontend hit the correct fun ...

Ways to verify a correct email address using ReactJS

I'm currently working on a project using React.js and Next.js. I'm encountering an issue with handling the Axios response in Next.js as it's displaying "[object Object]" instead of the actual response data. How can I properly handle the resp ...

Learn how to incorporate the prettier command into your coding workflow by adding it as a devDependency before committing code or

I am currently engaged in a React project. I am looking to set up autoformatting on save in my Visual Studio Code. However, I prefer not to adjust the settings within VSCode itself due to the variation in configurations among users. Instead, I want to ach ...

ng-if directive in AngularJs will not function properly if the condition text includes a space

I encountered an issue while attempting to set values in AngularJS UI grid based on the row.entity values. To address this, I created a cellTemplate that evaluates the row values and applies text styling accordingly. Code Snippet var statusTemplate=&apos ...

data-abide is flagging all fields as incorrect

Recently, I encountered an issue with a specific form I have created: <%= form_for(@building_shared_space, data: {abide:''}) do |f| %> ... <div class="field"> <%= f.label :room_type, 'Room Type' %> <%= ...

Tips for deactivating a single edit button

Is there a way to make it so that when I click on a checkbox, only that specific todo's edit button is disabled? Currently, clicking on a checkbox disables all edit buttons in the todo list. Any suggestions? class App extends Component { state ...

The appearance of the page varies when viewed on different computers using the same version of Firefox

Previously, I posed a question with a touch of irony regarding Firefox without providing an example. As a result, my question was downvoted and I had to request its removal. Now, I have an example illustrating the issue at hand. It took some time to clean ...

Managing the ajax response to showcase a button within datatables

Here is my current datatable structure: <table id="list" class="display" width="100%" > <thead> <tr> <th>Title</th> <th>Description</th> <th>delete</th> ...

"Utilizing AngulaJS to apply a class to the parent element when a radio button is

I'm wondering how I can assign a class to the parent div of each radio button in a group? You can find the code below and view the corresponding JSFiddle here. Here is the HTML: <div class="bd"> <input type="radio" ng-model="value" val ...

Transforming XML into Json using HTML string information in angular 8

I am currently facing a challenge with converting an XML document to JSON. The issue arises when some of the string fields within the XML contain HTML tags. Here is how the original XML looks: <title> <html> <p>test</p> ...

Dealing with AJAX errors in React components after mounting

Facebook suggests that the optimal method for loading initial data in a React component is to execute an AJAX request within the componentDidMount function: https://facebook.github.io/react/tips/initial-ajax.html It would look something like this: ...