The order of event capturing and bubbling phases is FLIPPED for the node triggering the event

Note: Using Chrome, works as expected in Safari. In summary, I thought I had a good knowledge of JavaScript. To test my skills, I decided to take a challenge and guess what happened:

We have an

<input type="button" id="btn">
with two event handlers added to it.

addEventListener('click', handler1, false);
addEventListener('click', handler2, true);

Inquiry: Which handler will be executed first?

My Assumption: It's simple, handler2 is set to run in the capturing phase, so it should execute first.

Reality: Execution order - handler1 followed by handler2.

It appears that for the node triggering the event, the sequence is bubbling before capturing phase starts.

In simpler terms, the capturing phase concludes AFTER the bubbling phase commences.

This contradicts the typical visualization we have when discussing capturing and bubbling: https://i.sstatic.net/OhcYz.jpg

Instead, the actual scenario seems more like this:

https://i.sstatic.net/Gilvx.jpg

Is there any insight or explanation on this from anyone?

Snippet:

const input = document.querySelector('#btn');
function handler1(e){alert("Hi from handler1, phase: Bubbling")};
function handler2(e){alert("Hi from handler2, phase: Capturing")};
input.addEventListener('click', handler1, false);
input.addEventListener('click', handler2, true);
<input type="button" id="btn" value="I'm clickable button"/>

Answer №1

https://www.w3.org/TR/DOM-Level-3-Events/#event-flow

When observing the value of "eventPhase", it becomes evident that it is currently in the "target" phase. During this phase, the specific choice for capturing does not have an impact as the event occurs neither during capture nor bubbling phases. The handlers are executed based on the order of attachment.

const input = document.querySelector('#btn');

//e.eventPhase: 1=Capture 2=Target 3=Bubbling
handler = (capture,e) => console.log(`eventPhase: ${e.eventPhase},`,`phase ${capture}`);
function handler1(e){console.log(`eventPhase: ${e.eventPhase},`,"Hi from handler1, phase: Bubbling")};
function handler2(e){console.log(`eventPhase: ${e.eventPhase},`,"Hi from handler2, phase: Capturing")};

input.addEventListener('click', handler.bind(null,'doesnt matter1'), !!Math.round(Math.random()));
input.addEventListener('click', handler1, false);
input.addEventListener('click', handler.bind(null,'doesnt matter2'), !!Math.round(Math.random()));
input.addEventListener('click', handler2, true);
input.addEventListener('click', handler.bind(null,'doesnt matter3'), !!Math.round(Math.random()));

document.body.addEventListener('click',handler.bind(null,'Bubbling'),false);
document.body.addEventListener('click',handler.bind(null,'Capturing'),true);
<input type="button" id="btn" value="I'm clickable button"/>

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

Eliminate nested object properties using an attribute in JavaScript

I am working with a nested object structured like this const data = [ { id: '1', description: 'desc 1', data : [ { id: '5', description: 'desc', number :1 }, { id: '4', description: 'descip& ...

Incorporating a secure and personalized "tracking code" feature into a PHP web application

My web application is built using vanilla PHP and MySQL, allowing registered users to create personalized profile pages. I want to implement a textarea form field in the control panel for users to input their custom tracking code (such as Facebook Pixel o ...

Encounter issue with async function in produce using Immer

Having an issue while attempting to create an asynchronous produce with immer. When calling the async function, this error is encountered: Below is my code snippet: import { combineReducers, createStore } from 'redux'; import produce from ' ...

What methods are available to trigger an AutoHotkey script using JavaScript?

I'm in the process of creating a Chrome extension designed to streamline tasks. I've come to a stage where I require my extension to execute certain AutoHotkey scripts. Is there a method to execute an AutoHotkey script using JavaScript? (I' ...

jQuery can be used to access and read the `$_FILES['name']['tmp_name']` data

I am working on an application to import Excel files into a database using excel_reader2.php. I have set up a form for uploading the Excel file, and once the desired file is selected, I need to read the data from the worksheet of the Excel file. However, I ...

AngularJS modal directives trigger a reset of $scope variables

I am developing a custom AngularJS application that needs to handle and store all the checkbox selections made by the user in a simple array of IDs. The functionality includes displaying a modal when the open button is clicked, allowing the user to perform ...

Integrating a <script></script> tag into the content method of fancybox2: A step-by-step guide

Currently, I am attempting to include a JavaScript content within the content method of fancybox. <script> $('#streaminput').on("click", function() { $('#streaminput').fancybox({ width : '95%', height ...

Tips for extracting a segment from an Object within an Array

I am looking to extract the datetime value from each element in the array below: [<time pubdate class="dt-updated" datetime="2015-07-09T11:50:32+0000" title="Time posted: 09 Jul 2015, 11:50:32 (UTC)" aria-label="Posted on 09 Jul">09 Jul</time> ...

Guide on utilizing AngularJS Filter service without HTML for Chrome extension development

Currently, I am attempting to utilize the filter service in AngularJS within my Chrome extension. However, I am unsure of how to properly obtain and inject it into my function. At this time, my code looks like: chrome.contextMenus.onClicked.addListener(fu ...

What is the best way to remove input focus when clicked away?

I am in the process of developing an application using next js, and I need assistance with designing a search field. The primary functionality I am looking to implement is displaying search suggestions when the user starts typing, but hiding them when the ...

Unable to see my Vue component within Laravel

My Vue component is not appearing on the screen and I am unable to identify the issue. I have checked my console for errors and I am using npm run hot Here is my app.js file: require('./bootstrap'); window.Vue = require('vue').default ...

Employing JavaScript to set a variable that changes dynamically

In my code, I have a functionality that allows for changing different dropdowns with similar ending IDs. In other parts of the code, I have assigned variables rl and rl_extra as well as rs and rs_extra. Now, when the var prefix is determined to be either ...

Is it possible to combine multiple jQuery selectors for one command?

I need some help with jQuery commands. I have two similar commands, but not exactly the same. Here are the commands: $("#abc > .className1 > .className2 > .className3"); $("#pqr > .className1 > .className2 > .className3"); Is there a w ...

Utilizing External Library Functions with VueJS

I have been looking everywhere for a working example of how to connect an external JS file and call its function, but I haven't had any luck. Essentially, my goal is to link an external JavaScript file and execute its function using VueJS. <script ...

What is the process for combining two distinct geometries with different materials into a single entity in three.js?

I created a 2D square line diagram followed by another square diagram with a sample image in the center position. However, one of them is visible while the other is hidden. I used two different geometries and materials - one with a line-based material se ...

What exactly is a doclet as defined in JSDoc documentation?

//Sample 1 /** * Here we have a simple function that returns a message * @param {String} msg The message to be returned * @returns {String} The message */ function showMessage(msg) { return msg } //Sample 2 /** * This is a function that also retur ...

The menu item fails to respond to clicks when hovering over the header background image

I'm having an issue with the Menu Link not working. I can click on the menu item when it's placed inside the body, but when I try to place it over the background header image, it stops working. Any help would be greatly appreciated. <div clas ...

What is the best method to ensure a jQuery function only runs once, even when declared multiple times within a form?

Whenever a button with a specific class is clicked in a document, a jQuery function is triggered to perform a certain action. See example below. $(document).on('click', '.tambah', function(){ alert('tombol tambah telah ditekan ...

Error in vis.js network: hierarchical layout caused by node quantity

I'm encountering an unusual issue that I can't seem to resolve by referring to the vis.js documentation. My network has a fixed hierarchy with a specific level defined for each node. I have a total of 51 nodes, and everything looks like this: ...

Dynamic banner featuring animated text, automatically resizing divs based on width while maintaining body width

Currently, I am working on creating a banner with moving text. While I have managed to come up with a solution for implementing this effect, there are two significant issues that I am facing. The width values in pixels need to be manually adjusted based ...