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!

$.bindalleventhandler('[action]', eventHandler);

eventHandler = function(trigger, element){
    if(trigger == 2 && $(element).attr('event') == 'change'){
        // execute action when change occurs
    }
    else if(trigger == 5 && $(element).attr('event') == 'keydown'){
        // execute action on keydown event
    }
    else{
        //default click
        // execute action by click
    }
}

HTML

<button action="action">click me</button>
<select name="name" action="action" event="change">
     <option value="value">name</option>
     <option value="value">name</option>
     <option value="value">name</option>
</select>

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:

function addEvent(element,event,callback) {
  if( !element.nodeName && element.length) {
    [].forEach.call(element,function(e) {addEvent(e,event,callback);});
  }
  else if( event instanceof Array) {
    event.forEach(function(e) {addEvent(element,e,callback);});
  }
  else if( callback instanceof Array) {
    callback.forEach(function(e) {addEvent(element,event,e);});
  }
  else {
    // do the actual event attaching here
  }
}

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

Or I can do something more complicated, like:

addEvent(
  document.querySelectorAll("input[type=date]"),
  ["focus","change","keyup"],
  function(e) {
    console.log(e.type+" event fired on "+e.target);
  }
);

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

Advertisement