What causes certain event handlers to be activated when using dispatchEvent, while others remain inactive?

When it comes to event-based JS, there are two main APIs to consider: event listeners and event handlers. Event listeners can be registered using addEventListener, while event handlers are typically registered with an API similar to

target.onfoobar = (ev) => { ... }
. Events can then be triggered using dispatchEvent. However, the exact timing and behavior of how dispatchEvent interacts with event handlers remains a bit unclear to me.

In my initial understanding, I believed that event handlers were invoked at the conclusion of dispatchEvent. This led me to imagine dispatchEvent functioning in a manner similar to this:

EventTarget.prototype.dispatchEvent = function(event) {
  // Initial dispatch to this.listeners, followed by:
  const handler = this['on'+event.type];
  if (handler) handler(event);
};

There are instances where dispatchEvent indeed triggers the event handler:

window.onclick = () => console.log("this IS called!!");
window.dispatchEvent(new Event("click"));

However, there are also scenarios in which dispatchEvent does NOT invoke the event handler:

window.onxyz = () => console.log("this is NOT called!!");
window.dispatchEvent(new Event("xyz"));

The inconsistency in these outcomes leaves me puzzled. What factors differentiate between these two situations? Is it possible that "click" is classified as a "standard" event type whereas "xyz" is not? If so, what exactly defines a "standard" event type, and how does dispatchEvent discern between them?

Answer №1

The reason why onclick works while onxyz doesn't is because onclick is integrated into the HTMLElement interface (via GlobalEventHandlers, which follows the UI Events specification). On the other hand, onxyz is simply a custom property without any tie to browser events.

Although custom events are supported, they do not have dedicated properties, so you must use the appropriate event registration method (addEventListener for modern systems or attachEvent for outdated versions of Internet Explorer):

window.addEventListener("xyz", () => console.log("this IS called!!"));
window.dispatchEvent(new Event("xyz"));

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

I made a request using the post type fetch to submit data to this form, but unfortunately, the server-side response returned

I encountered an issue where after sending the post type fetch to this form, I received 'undefined' on the server side. Here's the code snippet for my fetch request: const { text, id } = Data; fetch('http://localhost:3001/add' ...

What steps can be taken to resolve the vulnerability in webpack-pwa-manifest?

Looking for solutions to address the [email protected] and minimist vulnerability. I attempted removing node/modules and package-lock.json, followed by a fresh npm installation, but the issue persists. Any suggestions would be greatly appreciated. Scr ...

Problem encountered when transferring JSON data to PHP for file writing

After spending numerous hours researching potential solutions, I still can't seem to fix the issue at hand. Admittedly, I am fairly new to PHP, so it's possible that I am overlooking a small detail. The problem lies in the fact that I have a form ...

Creating dynamic selection options in an HTML select tag using PHP

When retrieving category and sub-category information from an API json file, the API returns category objects with a "parent" attribute. Main category objects have a parent attribute equal to 0, and sub-category objects have the parent attribute equal to t ...

Enhancing Next.js SEO with 'use client' Metadata

Currently, I am facing an issue with my product page. The metadata for this page is fetched from the backend using an API that retrieves data from a database. To fetch this data and update it on the client side, I am utilizing a custom hook. However, the p ...

The menu field remains open even after clicking on the menu

I have encountered an issue with my code. Here is a DEMO that I created on jsfiddle.net Currently, when you click on the red div, the menu opens. However, if you click on the menu items, the menu area does not close. What do I need to do in order to clo ...

I need assistance with a feature on my website where a new form is added every time the invite button is clicked, and the form is deleted when the delete button is

Invite.js This invite component includes an invite button outside the form and a delete button inside the form. The goal is to delete the form when the delete button is clicked. I have utilized useState and sourced this form from material-ui. Can anyone ...

Learn how to showcase a predetermined option in an HTML select element using Vue.js and Minimalect

I am currently utilizing Vue.js along with the Mininmalect HTML select plugin to showcase a list of countries by their names and values, where the value represents the 2 digit country code. Successfully, I have managed to implement the plugin for selectin ...

in the matchMedia addListener callback function, you can pass an argument

While working on a plugin that involves toggling certain behaviors on and off using matchMedia functions, I encountered an issue with passing arguments to my callback function. Whenever I try to pass an argument to the callback function, it returns as unde ...

Issue encountered: Unable to load resource - ajax file upload failed due to net::ERR_SSL_BAD_RECORD_MAC_ALERT error

I've implemented an AJAX form file upload using jQuery. After testing my code across multiple computers and browsers, I've encountered an issue on one Windows 8 machine running Chrome where the upload functionality fails with the following error ...

Localhost is unable to process AngularJS routes containing a dot in the URL

When using the route provider and setting this specific route: .when('/:name/:id', { It successfully navigates to my desired path and executes the code when I enter: https://localhost.myapp.com:9000/Paul/123 However, it fails to work with this ...

How can I use JavaScript to disable a table row and then save the selected option in a MySQL database?

I have a PHP snippet that dynamically displays table rows. Each row contains a radio button with "Yes" and "No" options. I have implemented a JS function where, upon choosing an option, a pop-up box is displayed. If the user selects the "Yes" option in t ...

Vue - Seamlessly Editing and Creating Content Together

When using Laravel, I am attempting to pass data to a Vue component. Depending on whether the user enters the component through an edit URL or a create URL, we send either an array of data or null. Here is an example of how this process works: Blade view ...

I'm experiencing an issue with fullCalendar where the dayRender function is not functioning as expected

I have been using fullCalendar and I am looking to customize the color of specific days. I have successfully created an overlay that is displayed when a user clicks on a particular day. Everything works as expected with the overlay, but now I am encounte ...

The filter() and some() functions are not producing the anticipated output

Currently, I am in the process of developing a filtering mechanism to sift through a dataset obtained from an API. The array that requires filtering contains objects with various parameters, but my aim is to filter based only on specific parameters. For ...

Save an automatically generated number into a variable and use it to reference an image file for display. This process can be accomplished using JavaScript

I'm having trouble getting my images to display randomly on a page. The images are named 0 - 9.png and I am using a pre-made function for random number generation. However, when I try to call on this function later down the page, nothing appears. It ...

How to manipulate iframe elements using jQuery or JavaScript

Hey there, I have a simple task at hand: I have a webpage running in an iFrame (located in the same folder on my local machine - no need to run it from a server) I am looking to use JavaScript to access elements within this iFrame from the main page. How ...

Working with repeated fields in Google protobuf in JavaScript

Consider this scenario: you have a google protobuf message called Customer with a repeated field as shown below. message Customer { repeated int32 items = 1; } What is the procedure for setting the repeated items field in javascript? ...

The integration of the jQuery library within the server side of a Google Apps Container Bound Script

Can the jQuery library be utilized server-side in a Google Apps Script that is Container Bound to a Doc or Sheet? If so, what steps should be taken? In a previous inquiry on Stack Overflow, I sought guidance on incorporating jQuery into a container-bound ...

Establish a global variable within a TypeScript file

I am currently facing an issue where I need to add an event to the browser inside the CheckSocialMedia function. However, it keeps saying that it could not find the name. So, my question is how do I make the 'browser' variable global in the .ts ...