Is it possible to have keyboard event listener canvas.addEventListener('onkeydown', ev_keydown, false);
like we have Mouse event Listeners
canvas.removeEventListener('mousedown', ev_mousedown, false);
canvas.addEventListener('mousedown', ev_mousedown, false);
in JavaScript. If not then what would be the alternate?
KeyboardEvent objects describe a user interaction with the keyboard; each event describes a single interaction between the user and a key (or combination of a key with modifier keys) on the keyboard. The event type ( keydown , keypress , or keyup ) identifies what kind of keyboard activity occurred.
// Add event listener on keydown document. addEventListener('keydown', (event) => { var name = event. key; var code = event. code; // Alert the key name and key code on keydown alert(`Key pressed ${name} \r\n Key code value: ${code}`); }, false);
A widget that calls a callback whenever the user presses or releases a key on a keyboard. A KeyboardListener is useful for listening to key events and hardware buttons that are represented as keys. Typically used by games and other apps that use keyboards for purposes other than text entry.
Keycode 13 is the Enter key.
Check if this works for you. Your sample line had the a prefix of on which is only used for IEs method attachEvent.
function listener(elem, evnt, func)
{
if (elem.addEventListener)
elem.addEventListener(evnt,func,false);
else if (elem.attachEvent) // For IE
return elem.attachEvent("on" + evnt, func);
}
listener(document.getElementById('myCanvas'), 'keydown', ev_keydown);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With