The event handler has now reverted back to its original undefined state

I'm having trouble with the following code snippet:

function dnd(){
}
var ele = document.getElementById("relative");
ele.addEventListener("click",dnd,false);
document.write(ele.onclick);

When I check the output, it shows as undefined. I expect it to be function onclick(event){dnd();}

Can anyone help me figure out a solution to this issue?

I would greatly appreciate any suggestions.

Answer №1

There are three popular methods for connecting events to DOM nodes.

The addEventListener() function is used to register event listeners following the W3C DOM standards. While it has numerous advantages, it is not compatible with Internet Explorer. To work with Internet Explorer, you must utilize the attachEvent() method, which provides similar capabilities.

Conversely, the onclick property is an older but more universally supported approach for attaching event handlers. However, it does have limitations, such as only permitting one event handler per event.

Regarding retrieving the event handlers linked to a specific node, it varies depending on the method employed to attach the events. The issue in your scenario arises from using the addEventListener() method to connect the event and then attempting to access it through the onclick property.

For further insights on this subject, especially the perspective shared by @Crescent Fresh, I recommend checking out the following Stack Overflow discussion:

  • How to find event listeners on a DOM node?

Answer №2

If the onclick property is set inline in the HTML markup (for example,

<div id="relative" onclick="alert('foo');" ></div>
), then you will be able to access the event handler.

However, it's rare that you would need to read or modify the event handler directly. It's not a common practice and could lead to unexpected behavior.

Answer №3

Implementing event handlers can be done in various ways, each utilizing unique mechanisms within the DOM. As you have noticed through your own experimentation, attaching an event listener with "addEventListener" does not interfere with the functionality of the "onclick" attribute on the element. These mechanisms operate independently from one another.

Answer №4

One of the drawbacks of the W3C event registration model is that if you use JS methods to register, there is no standard way to retrieve the handlers.

The most recent DOM LEVEL 3 Events specification from W3C introduces eventListenerList, but there seems to be limited support for this API across browsers.

However, if you add your method in the traditional way,





then your example will function as expected.

Here are some helpful StackOverflow links:

link text

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

Tips for effectively loading data of a specific user or event into a bootstrap modal in Laravel using AJAX

I'm having some trouble loading Event data into my bootstrap modal in Laravel. This is all new to me as I'm just getting started with AJAX. Can someone please take a look at what I've done so far? Modal Template <div class="modal fa ...

Rapidly generate VueJS templates for quick display

Is there a way, similar to KnockoutJS, to easily render content from a template using an ID? <script type="text/html" id="template-example"><span>Hello world!</span></script> <div data-bind="template: &a ...

Sequelize makes it easy to input records into various tables simultaneously

Embarking on my first experience with Sequelize and MySQL, I am seeking guidance on inserting data into two tables with a foreign key relationship. Let's delve into the structure of the entities - bookingDescription and bookingSummary. //bookingSumma ...

When filtering an array in JavaScript, ensure to display a notification if no items match the criteria

In React/Next, I have an array that is being filtered and sorted before mapping through it. If nothing is found after the filters run, I want to display a simple message in JSX format. The message should be contained within a span element. Here is the str ...

What is the reason in AngularJS for requiring directive attributes to be hyphen-separated while their scope variables are camelCased?

Here is an example in Html: <!-- Note 'display-when' is hyphenated --> <wait-cursor display-when="true"></wait-cursor> Then, when defining it in the directive: scope: { // Note 'displayWhen' is camelCased show: ...

In JavaScript, if a string matches a property in an array, then the array can be reordered with the

Currently, I am utilizing an Angular 5 pipe to manipulate an array before displaying it using ngFor. The array consists of all active users, and my goal is to ensure that the user who is currently logged in always appears at the beginning of the array so ...

The CSS3 slideshow is displaying distorted and unfocused images

I have a CSS code that controls the timing of my slideshow with 3 images: .slideshow li:child(1) span { background-image: url(../../pic/bg1.jpg); } .slideshow li:child(2) span { background-image: url(../../pic/bg2.jpg); -webkit-animation-de ...

Sequelize.js keeps the previous value for linked tables

My objective is to update the product status within the Product table. Each product has a statusId, which is either "1" or "2". The default value for statusId is always set to "1" for all products and should switch to "2" when the route is accessed once (a ...

What is the best way to display and conceal a loader in order to reveal additional posts?

How can I display a loader when the user clicks on the "load more posts" button, show it while the posts are loading, and hide it once the posts have been successfully loaded? Additionally, I want to show the loader again when the user clicks on the button ...

Restore the button to its original color when the dropdown menu is devoid of options

Is it possible to change the button colors back to their original state automatically when a user deselects all options from my dropdown menu? The user can either uncheck each option box individually or click on the "clear" button to clear all selections. ...

Clearing a textarea in jQuery

I'm experiencing an issue that I can't seem to resolve on my own. Any assistance would be greatly appreciated. My function designed to clear a textbox upon click doesn't seem to be working correctly: $(function() { $('textarea#co ...

Determine if the user's intention is to tap or to scroll up and down the page on a touch-sensitive device

When a user taps outside of a popup-div (touchstart), the popup should be hidden. However, if the user's intention is to scroll/swipe (touchmove), the popup should not be hidden. Can you provide a code example that can detect and handle these two ac ...

Add HTML to a div element using jQuery when content is replicated through JavaScript

I have encountered an issue while appending HTML from a dynamically created div using JavaScript. The problem arises when I try to append the HTML multiple times - each time it adds the content twice, thrice, and so on. This is possibly happening because i ...

JavaScript nested function that returns the ID of the first div element only upon being clicked

I am facing an issue with a function that returns the id of the first div in a post when an ajax call is made. The problem is that it repeats the same id for all subsequent elements or div tags. However, when the function is used on click with specified ...

Error encountered when using the Jquery append function: Anticipated ')' issue

While working on my PHP file, I encountered an issue with an AJAX request. The request is returning the correct value, however, when attempting to use the append function in jQuery, it results in an error being displayed in the console. $.ajax({ ...

Performing synchronized execution in a node.js application by utilizing the 'readline' package

Struggling with the asynchronous nature of node.js, despite hours spent on callbacks and researching. I have a program that reads lines from a file using the readline module in node, passing data to async functions within the program. The goal is to proces ...

The variable from AJAX is not being displayed in PHP

Need help with transferring a JavaScript variable to the same PHP page. The following code is what I have so far: <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script& ...

displaying only the date in bootstrap-datetimepicker

I am currently utilizing the repository created by smalot, and my intention is to choose and display dates only (while in other instances I showcase both date and time, hence utilizing this repository). Although I have succeeded in selecting dates only, th ...

"Unraveling Loopback: The Ultimate Guide to Accessing Every Role Assigned to a

Currently, I am in the process of developing a Loopback application where I have customized a user model based on the pre-built User model. { "name": "user", "base": "User", "idInjection": true, "properties": { "test": { "type": "string" ...

Tasks should be defined prior to being referenced in order to avoid any issues

Utilizing multiple files with gulp@4, the main gulpfile.js includes all other files within the ./tasks/ directory. We have implemented the npm gulp-hub package to incorporate multiple gulpfiles within the ./tasks/ directory. However, upon calling the tasks ...