How to create shortand for addEventListener

I want to create a shortand for addEventListener, the code I’m trying is:

var dom = {
  id: function(elementId) {
    return document.getElementById(elementId);
  }
};
dom.id.on = function(event, options) {
  var id = id.elementId;
  return id.addEventListener(event, function() {
  options;
}
}

When I use it like that:

dom.id('paragraph').on('click', dom.id('paragraph').innerText = 'clicked');

It instantly changes it’s innerText to clicked, without I even clicking it.

17 thoughts on “How to create shortand for addEventListener”

  1. Wrap your dom.id('paragraph').innerText = 'clicked' in a function:

    dom.id('paragraph').on('click', () => {
      dom.id('paragraph').innerText = 'clicked';
    });
    
    Reply

Leave a Comment