Pregunta

I been reading articles about game development in HTML5 canvas but none of them are usually optimized. While reading multiple articles I have found different methods of have key listeners in javascript. First one I found

window.addEventListener(
"keydown",
eventReaction,
false
);

Second one I found

document.onkeydown = function(e) {
//do stuff with this
};

What are the differences between them? Which one is the proper one to use or fastest? I do not want to use a deprecated method, I just want to use the one that is proper for html5 canvas... If this is a bad question please do not -rep me, just tell me and I'll remove it.

¿Fue útil?

Solución

The second piece of code you specify a listener directly on the HTMLElement.
This is not deprecated but it's not the way to go.

document.onkeydown = function(e) {
//do stuff with this
};

The first piece you specify a listener for an HTMLElement. This way you can specify multiple events for an action.
This is definitely the way to go.

window.addEventListener("keydown",eventReaction,false);

Note: addEventListener is supported for modern browsers and IE>8

PS: Bad questions don't exist, only bad answers ;)

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top