Skip to content
Advertisement

How to create a single event handler for a variety of events in JavaScript

I want to do the following with JavaScript/jQuery:

JavaScript

Pseudo code!

JavaScript

HTML

JavaScript

Someone knows where to start? It has to be AJAX proof just like the jQuery $.on() method.

I only want this for a variety of events and bind it to elements containing the action attribute. Maybe I just parse the HTML and then dynamically create event handlers but then I have to parse every AJAX call.

Disclaimer: I am not asking you to make code for me but to send me in the right direction.

Advertisement

Answer

Let me show you the general idea of how my custom-built addEvent function works:

JavaScript

Basically, this allows me to pass something simple like
addEvent(document.body,"click",function() {alert('Hi!');});

Or I can do something more complicated, like:

JavaScript

You should be able to adapt my approach to your needs 🙂

Advertisement