How to add onkeydown to the body?

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

Any idea how to do this?

 <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();" > 
+4
source share
3 answers

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

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

Here is an example:

Javascript

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

Live demo

The above code can be placed in any valid JavaScript block (e.g. Main.onLoad() ).

+3
source

You can connect listeners as follows: you can pass a function or just call an anonymous code.

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

It seems that work on stack overflow is being passed to the console.

0
source

onkeydown can usually be attached to elements that can receive focus. In some browsers, you can focus on document.body , but you cannot rely on it. window is one of those elements that can get focus.

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

 window.onkeydown = TVA.keyDown; 

Or when using addEventListener() :

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

Source: https://habr.com/ru/post/1490894/


All Articles