Search code examples
javascriptjquerychaining

how to add two event handlers to a element or node in combined form?


I know that in jQuery we can add multiple event handlers in combined form but how to do it in pure Javascript?

How can we attach event handlers in combined form like this:

document.getElementsByTagName('input')[0].onclick.onkeypress = function() {
    alert(1);
}

But It throws a typeError.


Solution

  • jQuery lets you be more concise but this isn't really different :

    var e = document.getElementsByTagName('input')[0];
    e.onclick = e.onkeypress = function() {
        alert(1);
    };
    

    And if you want to avoid polluting the global namespace with the element, do this :

    (function(){
      var e = document.getElementsByTagName('input')[0];
      e.onclick = e.onkeypress = function() {
        alert(1);
      };
    })();
    

    You could define a function to add chaining to addEventListener but is there really a point ?