1

In hyperapp code base we could able to see the line:

https://github.com/hyperapp/hyperapp/blob/master/src/app.js#L135

which shows:

  try {
    element[name] = value
  } catch (_) {}

Apparently, element is an HTMLElement and value is a function! The interesting part here is that, if name is say for example onclick and value is a function which does prints something to the console, the above code correctly adds the event listener for onclick.

I was wondering whether is this a short hand for addEventListener or I'm wrong here?

glennsl
  • 28,186
  • 12
  • 57
  • 75
batman
  • 3,565
  • 5
  • 20
  • 41

2 Answers2

5

I was wondering whether is this a short hand for addEventListener...

No. It's the old DOM0 style event handling that predates it. If you assign a function to element.onclick or element.onmouseover, etc., it sets up that function as an event handler.

What's different about this from addEventListener is that only one function can be set up this way; if you do it a second time with a second function, it replaces the first. In contrast, addEventListener can be used to play nicely with others, allowing multiple handlers.

(Another difference is that the onxyz style worked on old IE, which didn't support addEventListener [but did support its Microsoft-only predecessor, attachEvent]. So old cross-browser code would frequently use the onxyz-style if playing nicely with others wasn't necessary. FWIW, if you still have to support IE8 or IE9-IE11 in their broken "compatibility mode," you can use the hookEvent function in this answer, which uses addEventListener or attachEvent if possible.)

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
1

It's sort of a shorthand for addEventListener but with one major drawback: you can only have one handler.

function firstHandler() {
  console.log('#1');
}

function secondHandler() {
  console.log('#2');
}

let onclickEl = document.getElementById('onclick');
let addEventListenerEl = document.getElementById('addEventListener');

// We can bind multiple event handlers using addEventListener
addEventListenerEl.addEventListener('click', firstHandler);
addEventListenerEl.addEventListener('click', secondHandler);

// But watch what happens when we do the same with onclick
onclickEl.onclick = firstHandler;
onclickEl.onclick = secondHandler;
<button id="addEventListener">addEventListener</button>
<button id="onclick">onclick</button>

For this reason, in your own code, I'd suggest always using addEventListener.

Mike Cluck
  • 31,869
  • 13
  • 80
  • 91