Event handler vs addEventListener

Hi there,

I don’t really get the difference between let’s say
view.onclick = textChange;
and
view.addEventListener(‘click’, textChange);

When do I have to use addEventListener? And why is the event name different in both cases? onclick vs click?

1 Like

Here we have an event binding on view.

view.addEventListener(‘mouseover’, colorChange);

Here we add another listener to the same node. Now it has two listeners (event bindings) and two handlers, assuming the other exists.

Just to venture down the rabbit hole… What if addEventListener accepts an object, so we can add multiple events? Worth trying, even if it doesn’t work. Then we’ll know.

view.addEventListener({
  ‘mouseover’: colorChange,
  'mousedown': borderChange
});

We still have to write those two callbacks for testing purposes.

'click' is the lexical name of the event. 'onclick' is the global event. We can only attribute singular global events to an object. Once we say object.onclick=callback we cannot bind another global event to that object by assignment. We’ve used up that card.

1 Like