GibboK
GibboK

Reputation: 73918

How to add onkeydown to body?

In my index.html I have this code. I would need to add onkeydown event to that body in Main.onLoad().

Any idea how to do it?

<body id="body" 
    onload="Main.onLoad();" 
    onunload="Main.unload();" 
    onmousedown="Main.mouseDown();"
>

<body id="body" 
    onload="Main.onLoad();" 
    onkeydown="TVA.keyDown(event);" 
    onunload="Main.unload();" 
    onmousedown="Main.mouseDown();"
>

Upvotes: 7

Views: 38963

Answers (3)

Teemu
Teemu

Reputation: 23396

Usually onkeydown can be attached to the elements which can receive focus. In some browsers you can gain focus to the document.body, but you can't rely on that. window is one of those elements which can gain the focus.

You can try to put the code below to the head section of your HTML code, after TVA is defined.

window.onkeydown = TVA.keyDown;

Or when using addEventListener():

window.addEventListener('keydown', TVA.keyDown, false);

Upvotes: 0

Jeff Noel
Jeff Noel

Reputation: 7618

In a Javascript block, try to use window.onkeydown (MDN).

You can also use document.onkeydown and document.body.onkeydown.

Here is an example for you:

JavaScript

document.body.onkeydown = function(e){
    alert(String.fromCharCode(e.keyCode)+" --> "+e.keyCode);
};

Live Demo

The code above can be put in any valid JavaScript block (such as Main.onLoad() function).

Upvotes: 8

raam86
raam86

Reputation: 6871

You can attach listeners like this: you can pass a function or simply invoke an anonymous one in code.

document.body.addEventListener('keydown',Main.onLoad);

Seems to work on stack overflow when passed to console.

Upvotes: 0

Related Questions