Skip to content
Advertisement

How to add listener for a custom event in the DOM?

What I want is to create my own function that will be bound as an event listener similar to how other event listeners (e.g., onclick) are set:

JavaScript

Is it possible and if so how?

Advertisement

Answer

The problem you have is the browser does not realize it is a function in there. It is a string, the only way you can make it a function is to assign it as a function.

One way is either on document ready or onload, you query the document for elements with the attribute and reassign it.

HTML

JavaScript

JavaScript

JavaScript

Example running here

This code uses querySelectorAll which is not supported in all browsers.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement