How can I identify an event occurring on two sibling elements that are overlapping?

I have 2 overlapping siblings as shown below:

document.querySelector("#item1").addEventListener('mouseup',()=>{
    console.log("Mouseup item 1!");
});

document.querySelector("#item2").addEventListener('mouseup',()=>{
console.log("Mouseup item 2!")
},true);
#item1{
  height:10rem;
  width:10rem;
  background-color:red;
  position:absolute;
  z-index:-2;
  
}

#item2{
  height:10rem;
  width:10rem;
  background-color:green;
  position:relative;
  top:2rem;
}
<div id="item1"></div>
<div id="item2"></div>

Whenever I click on item2, I want the mouseup event of item1 to also be triggered if the mouse is within item1.

In essence, I want the mouseup event to be activated on whichever div the mouse is inside, regardless of overlapping positions. How can I achieve this functionality?

Answer №1

After reading a suggestion from @Teemu in the comments about using the `elementsFromPoint` method, I crafted the following solution:

document.querySelector("#wrapper").addEventListener('mouseup', (event) => {
  let els = document.elementsFromPoint(event.clientX, event.clientY);
  els.forEach(el => {
    if (el.id != '' && el.id != 'wrapper')
      console.log(el.id)
  })
});
#item1 {
  height: 10rem;
  width: 10rem;
  background-color: red;
  position: absolute;
}

#item2 {
  height: 10rem;
  width: 10rem;
  background-color: green;
  position: relative;
  top: 2rem;
}

#wrapper {
  background-color: blue;
  height: 20rem;
  width: 20rem;
}
<div id="wrapper">
  <div id="item1"></div>
  <div id="item2"></div>
</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

"Implementing a column template in jqgrid post-creation: A step-by-step

Can't apply column template with Free jqgrid once it's been created. I've attempted: var newOrderPriceTemplate = { align: "center", formatter: "showlink", formatoptions: { onClick: function() { alert('clicked&apos ...

Is there an easier method to assign text to a modal-body using a specific classname?

Utilizing Bootstrap 5.1.3 alongside Pure Vanilla JavaScript, I have successfully been able to populate the .modal-body with content using the following code: function showBSModal(modalid, inputid) { var myModal = new bootstrap.Modal(document.getElement ...

I'm looking for some clarity on incorporating <SpeedInsights /> into NextJs14. Can anyone shed some light on

While working on my NextJs project, I attempted to integrate Vercel Speed Insight import { SpeedInsights } from "@vercel/speed-insights/next" <SpeedInsights /> An error related to hydration is being returned. I am looking for an explana ...

What is the process for dynamically altering the method in a class?

Is there a way to dynamically modify the changeThis method by substituting it with the value of a radio element? For example, if I select event1, the method should be switched to Class.event1() <input type="radio" class="radio-input" ...

Is it possible to use the Three.js LoadingManager to load videos?

I am currently using THREE.LoadingManager in conjunction with various loaders to efficiently handle the loading of textures, models, images, and cubeTextures before my app is displayed. This setup enables me to present a loading bar that shows the overall ...

Receive real-time updates from the query and then provide the results using Vuex and Firestore

I have encountered an issue while trying to retrieve data from a Firestore real-time query and perform other actions. Although I am able to receive the data from Firebase as an Object, I am facing a problem when trying to access the properties of the retur ...

Updating a post in Vue.js using its unique id

Recently, I delved into the world of vue.js and stumbled upon this intriguing question on Stack Overflow. It provided some valuable insights on how to fetch posts from a database using v-for. Upon loading each post, I noticed the presence of Edit and Dele ...

Creating a hover effect on a specific area of a map is a useful technique

Can someone please help me create a hover effect for areas in maps? Below is the code for the map. Thank you in advance! Here is the image. <img src="[CR_kraje_1_úroveň_v1] (imported)" width="770" height="443" border="0" usemap="#map" /> &l ...

Using the HtmlTable Control to populate data from an HtmlTable object in ASP/C# Programming

It seems like a simple question, but I'm struggling to populate an HtmlTable control, accessible from codebehind, with data from an HtmlTable object already containing information. Could someone offer me guidance on this issue? Thank you in advance. ...

Missing RequestVerificationToken value when hiding HTML element using jQuery

I am encountering an issue with my ASP.NET MVC 4 form that involves checkboxes being used to show and hide certain HTML elements. When I initially visit the form page, the RequestVerificationToken value is correctly created as a hidden field. Some HTML ele ...

Extract the price value from the span element, then multiply it by a certain number before adding it to a div element

On the checkout page of my website, I have the following HTML: <tr class="order-total"> <th>Total</th> <td><strong><span class="woocommerce-Price-amount amount"> <span class="w ...

Converting a JSON array stored in a local file to a TypeScript array within an Angular 5 project

I'm currently working on developing a web app using Angular 5. My JSON file has the following structure: [ { "id": 0, "title": "Some title" }, { "id": 1, "title": "Some title" }, ... ] The JSON file is store ...

What sets apart the intended usage of the DOM `hidden` from the CSS `visibility` property?

Exploring the DOM property hidden and the CSS property visibility, I find myself unsure of when to utilize each one. What are the distinctions in their intended purposes? While they may serve similar functions, I am curious about the underlying motivation ...

Is it possible to align the second "navbar" div inline with the first "navbar" div?

I am struggling to align the div "nav2" on the same line as "nav1", but it just won't move up. I've tried using float, but it's not working. * { padding: 0; margin: 0; box-sizing: border-box; } body { width: 100%; height: 100vh; } #navb ...

Combining two arrays of objects in JavaScript to create a new array, using the properties of the objects

I am facing an issue with handling two arrays of JSON objects in JavaScript. I am trying to create a new array by mapping on the "Word_No" property of both arrays. Here is an example of how the arrays look like: wordInfo (total length: 4000): [ { ...

Ways to populate dynamic choices for multiple Select boxes within an ng-repeat loop

When I click the "Add Row" button on an Html form, dynamic rows are added. Each row contains a 'Country' select and a 'State' select. The issue I am facing is that when I select a country in one row, all other row values change as well. ...

Utilize jQuery to showcase elements in a dropdown menu

Hey everyone, I'm working on an ASP.NET MVC4 project and I'm using a jQuery script on the edit page. However, I am encountering an issue with displaying elements on the page. Here is the initial HTML markup of my dropdown before any changes: & ...

What is the best technique for creating a preloader that can seamlessly fill the background of a vector image?

I am looking for guidance on creating a CSS3 preloader using a vector image. My goal is to have the logo start off transparent with only the border visible, and as the loading occurs, fill in from bottom to top with the background color. Thank you to ever ...

Leverage the power of React in tandem with Express

My web site is being created using the Express framework on NodeJS (hosted on Heroku) and I'm utilizing the React framework to build my components. In my project, I have multiple HTML files containing div elements along with React components that can ...

Stop the duplication of the HTML content to ensure only one copy is saved

Recently, I have been coding a feature that saves the HTML of the currently displayed page to another file upon pressing a button. However, I encountered an issue where if the button is pressed multiple times quickly, the saved file contains incorrect HTML ...