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

What is the reason behind React deciding to skip the final question, even though it has been accurately saved to the

A simple web application was developed to calculate risk scores by asking five questions, with additional points awarded if a checkbox is checked. Despite extensive hours spent debugging, a persistent bug remains: the final question does not appear on the ...

The getElementById function can only select one option at a time and cannot select multiple options

I'm having an issue with a JavaScript function that is supposed to allow me to select multiple options, but it's only selecting the first one. Here is the JavaScript code: function index(){ var a="${staffindex}".replace("[",""); ...

Searching for substrings in NodeJS using Express

In this code snippet, I am using Express JS and AES256 encryption to encode and decode simple text strings with a predefined key. The Express JS web server is set up to display specific elements based on the URL content. For instance, if the URL was abc. ...

Removing HTML tags from a string while preserving specific tags in JavaScript

Here is a JavaScript string that I am working with: var test = "<p>test</p> FOLER.PRODUCTS<12345><level-2>"; I'm trying to remove the HTML tags from the string because the service I'm using doesn't accept them. Here ...

How can I manage the asynchronicity of Hapi.js, fs.readFile, fs.writeFile, and childProcess.exec?

My code execution seems to be resulting in an empty list, could it be that my asynchronous calls are incorrect? I've tried rearranging and breaking things into functions but there still seems to be a timing issue with my execution. The order in which ...

Creating a wrapper component to enhance an existing component in Vue - A step-by-step guide

Currently, I am utilizing quasar in one of my projects. The dialog component I am using is becoming redundant in multiple instances, so I am planning to create a dialog wrapper component named my-dialog. my-dialog.vue <template> <q-dialog v-bin ...

Error: The specified module is missing an export that was requested

Hello, I encountered an error in my console that reads: "Uncaught SyntaxError: The requested module './components/tileHeader/controller.js' does not provide an export named 'tileHeader'". Below is the code snippet causing the issue: co ...

Updating classes when useState changes in React JS

I'm currently working on implementing a carousel slider in React. As I track the state to determine the specific class to add based on the state value (e.g., adding "-left-1/3" when the state is 2), everything seems to be functioning correctly. Howeve ...

Looking to display an alert message upon scrolling down a specific division element in HTML

In the midst of the body tag, I have a div element. <div id="place"> </div> I'm trying to achieve a scenario where upon scrolling down and encountering the div with the ID "place", an alert is displayed. My current approach involves che ...

What is the best way to create a slideshow using an IFrame?

Currently seeking a solution for an iframe slideshow that can smoothly transition between multiple HTML iframes. I have a total of 5 iframes that need to rotate automatically and continuously. Any suggestions on how to build a lively and dynamic iframe sl ...

Arrange a cluster of CSS table cells onto a fresh line

Currently, I am exploring CSS properties to create the visual appearance of a table using two levels of DOM elements. The highest-level element wraps around its child elements, which are styled to resemble a flat list. For example: <div class="t"> ...

Utilize React to iterate through a dictionary and display each entry

Essentially, I am pulling data from my API and the structure of the data is as follows: { "comments": [ { "user": "user1" "text": "this is a sample text1" }, { "user": "user2" "text": "This is a simple text2" }, } ...

do not display bullet points

The bullets from the list-style type are not appearing. Despite the CSS code never declaring list-style-type: none, I have specifically declared list-style-type: disc for the section in question. I even checked with Firebug and other tools, and it is evide ...

What could be causing the lack of response from PHP Ajax?

In the midst of tackling my college project, I find myself working on a webpage that is designed to showcase City and temperature information. To accomplish this task, I am delving into the realm of AJAX in order to dynamically update the temperature at sp ...

Dynamically scrolling using SuperScrollorama and Greensocks

I'm currently facing a JavaScript animated scroll challenge that has me scratching my head. My approach involves using the SuperScrollorama jQuery plugin, which relies on the Greensock JS tweening library. The main effect I'm aiming for is to " ...

Inquirer doesn't waste time lingering for user input following a prompt

After initiating the prompt, I'm encountering an issue where inquirer doesn't pause for user input and instead immediately advances to the next command line. Below is the code I'm using: import inquirer from 'inquirer'; var link; ...

Is it possible to make changes to dynamically inserted HTML using jQuery.ajax?

I'm facing a scenario in jQuery where I make an ajax call that inserts HTML into my website. However, I also need to perform operations on this inserted HTML within the same ajax call's success callback function. Here is a simplified version of ...

Attempting to align a CSS card flip within a Bootstrap layout

I have created a card using HTML and CSS, but I am struggling to make it line up with Bootstrap. Currently, the card is only in the middle of the section and I can't seem to figure out how to get four of these cards to line up in one row, and then ano ...

Using Vue.js to implement dynamic table rowspan functionality

Has anyone experimented with implementing dynamic table rowspan in vue.js? Here is the sample data { date: '2018-08-14', temp_que : 120, }, { date: '2018-08-14', temp_que : 120, }, { date: '2018-08-15', ...

Sharing application state between different routes in React Router v4 can be achieved by using methods such

I'm seeking solutions to address the following challenge: Without utilizing any state management library, I solely rely on React. The primary application state is contained within the <MyFoodApp/> component, which includes an array of restaura ...