Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

keyboard Event Listener In JavaScript

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?

like image 215
james Avatar asked Apr 07 '12 18:04

james


People also ask

What is keyboard event in Javascript?

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.

How do I add an event listener to my keyboard?

// 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);

What is a keyboard listener?

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.

What is e keycode === 13?

Keycode 13 is the Enter key.


1 Answers

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);
like image 148
MrMortales Avatar answered Oct 23 '22 03:10

MrMortales