What is the reason behind event bubbling failing to function properly when CSS grid is utilized and elements are placed in the same cell

I am facing an issue with two grid children occupying the same cell and both having click event listeners. As per the concept of event bubbling, I expect both event listeners to be triggered when I click on the cell.

const outer = document.getElementById('outer')
outer.addEventListener('click', () => console.log('on outer click'))

const inner1 = document.getElementById('inner1')
inner1.addEventListener('click', () => console.log('on inner1 click'))

const inner2 = document.getElementById('inner2')
inner2.addEventListener('click', () => console.log('on inner2 click'))
#outer {
  width: 100vw;
  height: 100vh;
  display: grid;
}

#inner2 {
  grid-column: 1/2;
  grid-row: 1/2;
}

#inner1 {
  grid-column: 1/2;
  grid-row: 1/2;
}
<div id="outer">
  <div id="inner1">

  </div>
  <div id="inner2">

  </div>
</div>

Playground: https://jsfiddle.net/o10sfpwu/

Expected log:

on inner2 click
on inner1 click
on outer click

Actual log:

on inner2 click
on outer click

Why is the inner1 event listener not fired? Shouldn't the click event bubble through all elements in this space?

Answer №1

Do all elements in this space receive the click event as it bubbles through?

No, only the DOM ancestors of an element will receive the click event as it bubbles up. The position of the element and whether it overlaps with another element are not considered during event bubbling.

For example, if 'inner2' is on top of 'inner1' in the same cell and 'inner2' comes after 'inner1' in the DOM, clicking on that cell will trigger the event on 'inner2'. Looking at the ancestors of 'inner2', we see:

<div id="outer">
  <div id="inner1">

  </div>
  <div id="inner2">

  </div>
</div>

However, only '#outer' (along with document.body and document.documentElement) are ancestors of 'inner2'. Since 'inner1' is not an ancestor and the event was dispatched to 'inner2', the event does not bubble through 'inner1'.

This behavior is explained in more detail in this MDN link:

During the bubbling phase:

  • The browser checks for onclick event handlers on the clicked element and runs them.

  • Then it moves to the next immediate ancestor and repeats the process until it reaches the root element.

Answer №2

Although the previous response adequately addressed your inquiry, I would like to redirect you (as well as any potential future readers) to document.elementsFromPoint, which may better suit your needs:

const container = document.getElementById('container')
container.addEventListener('click', (e) => {
  const elements = document.elementsFromPoint(e.clientX, e.clientY);
  elements.forEach( (el) => console.log('clicked on', el));
});
#container {
  width: 100vw;
  height: 100vh;
  display: grid;
}

#box2 {
  grid-column: 1/2;
  grid-row: 1/2;
}

#box1 {
  grid-column: 1/2;
  grid-row: 1/2;
}
<div id="container">
  <div id="box1">

  </div>
  <div id="box2">

  </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

Is there a way to harness the getUserMedia() API in Node.js for seamless real-time media streaming?

Discovering how to capture video and audio directly in my web browser was surprisingly easy after a quick online search. I found a basic example that successfully demonstrated video and audio playback: navigator.getUserMedia = (navigator.getUserMedia || ...

What is the best way to implement a scroll event in a React application?

Can someone provide guidance on how to properly write the scrollHandler function for this scenario? ` useEffect(() => { document.addEventListener('submit', scrollHandler); return () => document.removeEventListener('scroll', ...

I'm looking to generate a semicircle progress bar using jQuery, any suggestions on how

Hi there! I'm looking to create a unique half circle design similar to the one showcased in this fiddle. Additionally, I want the progress bar to be displayed in a vibrant green color. I've recently started learning about Jquery and would apprec ...

Leveraging the power of jQuery Ajax in conjunction with node.js and express for email validation functionality

Hey there! I have a contact form on my website that uses ajax for validation and email sending. The issue is that the validation file is set up for PHP, but I'm trying to make it work with my NodeJS app. Unfortunately, when I tried modifying the ajax ...

Issue with JavaFX: Unable to remove additional space on the right side of TabPane

While developing a full-screen application on JavaFX 2.2 with tab navigation, I encountered an issue where there is a 10px space at the right side of the headers region. Surprisingly, this space only appears after switching to the last tab and disappears w ...

Switch over to TypeScript - combining Socket.IO, Angular, and Node.js

This is the code I'm using for my node server: import http from 'http'; import Debug from 'debug'; import socketio, { Server } from 'socket.io'; import app from './app'; import ServerGlobal from './serve ...

Why does my 'click' event listener only work for the first two <li>'s and not the others?

I am new to programming and recently achieved success with my 'click' eventListener. When clicking on the first two li elements within the ul, the class of the div toggles on and off as expected. However, I encountered an issue where clicking on ...

Using a media query in conjunction with an image map

Can anyone help me figure out why this media query isn't working as expected? I am attempting to remove the top 150px of an image map if the browser width is larger than 1300 pixels. The image map itself is responsive and expands with the browser widt ...

Analyzing the markup within the React-Mentions package

I am currently utilizing the 'react-mentions' library to mention names from a database. However, the data format that is being returned is quite peculiar. I am now looking to transform this data into a JSON format. Here is the code I have: <M ...

I'm confused why this code is functioning in JSFiddle but not on my HTML webpage

For the first time, I am encountering this issue. I am currently attempting to integrate this code into my application http://jsfiddle.net/TC6Gr/119/ My attempts include: Pasting all the jsfiddle code in a new page without my code, but it doesn't w ...

What causes the focus to be lost when hovering over the second item in the sub list

Link to Fiddle: https://jsfiddle.net/n3tzbn4o/3/ Snippet of CSS: /* Styling for Menu element */ .menu { position: relative; z-index: 100; height: 40px; width: 100%; } Whenever the cursor hovers over Menu 3 > '2015' > Assesmen ...

Move the scroll bar outside of the div and set it to automatically overflow

My issue involves a small div with the CSS property overflow:auto;. However, when the scroll bar appears, it covers up a significant portion of the div. One possible solution is to use overflow:scroll;, but this can result in an unsightly faded scroll bar ...

How does margin:auto differ from using justify-content and align-items center together?

If you want to center both horizontally and vertically at the same time, there are two easy methods available: Option One .outer { display:flex; } .inner { margin:auto; } Option Two .outer { display: flex; justify-content: center; align-items ...

Firefox version 78.0.1's Responsive Design Mode fails to provide accurate window.innerWidth values after screen orientation change

Could this be a bug specific to Firefox, or have I made an error somewhere? When testing in Chrome or on an actual device like Android, everything works fine. It appears to be an issue only when using Firefox's Responsive Design Mode. Below is the c ...

"Pair of forms and buttons to enhance user experience with Bootstrap and

Experiencing an issue with my webpage that is built using HTML, Bootstrap, and PHP. The page contains two forms: a contact form and a distribution form within a modal. The problem lies within the distribution form as clicking the button only submits the ...

Upgrade angular-chart.js when applied to a filtered collection

I recently started working with Angular and encountered an issue while incorporating Angular Charts JS. I have a list that can be filtered using search text, and I want my charts to update whenever the list is filtered. What would be the best approach to ...

"jQuery Hide-and-Seek: A Fun Way to Manip

I am facing a challenge with a set of divs that I need to dynamically show and hide based on user interactions with questions. Essentially, the user will be presented with a question. Based on their answer, specific content with a title and description wi ...

Implementing functions on React component classes

Recently, I decided to convert a slideshow from w3s schools into a React component. The process involved changing all the functions into methods on the class and setting the initial state to display the first slide. However, upon clicking the buttons or do ...

Transform the entire division into a clickable link, excluding a specific subdivision that should have its own separate link

I need to create a product layout page where products will be displayed with an image, person's name, title, and description. The challenge is that all of these elements should have one common link except for the person's name that needs a separa ...

External UI library for AngularJS

Exploring the realm of animations using Angular and Masonry (UI library) has been quite a journey. I've encountered an issue where animating an element located outside the ng-view works perfectly fine, but the same animation doesn't seem to work ...