Search code examples
javascriptdomeventsdom-eventsdecorator

How to decorate a DOM node's event handler?


How can you decorate a DOM node so that you add an event handler, but within the new handler you can call the previous handler?


Solution

  • I assume that you are binding events in the way element.onclick = function () {};.

    Yes, you can make a function that wraps previous event handlers and execute them sequentially, e.g.:

    function addEvent(el, event, handler) {
      var oldEvent = el['on'+event];
      if (typeof oldEvent != 'function') {
        el['on'+event] = handler;
      } else {
        el['on'+event] = function() {
          oldEvent();
          handler();
        }
      }
    }
    
    var el = document.getElementById('el');
    addEvent(el, 'click', function () { alert('1'); });
    addEvent(el, 'click', function () { alert('2'); });
    

    Check the above example here.