laserpanda
laserpanda

Reputation: 387

brain freeze - cant catch keystrokes with javascript

I know its really simple, but why doesn't this code alert on key presses?

Tried with both Chrome and Firefox.

<html>
<head></head>

<body style="height: 100%; margin: 0px; padding: 0px;">

<div style="height: 100%;" id="main">sds</div>

<script>
window.onload = function() 
{
var m = document.getElementById("main");
m.onkeydown = function(event) { alert("keydown!"); };
m.focus();
};
</script>
</body>
</html>

thanks

Upvotes: 0

Views: 34

Answers (1)

pid
pid

Reputation: 11597

You shouldn't catch key presses on an element unless it is an <input> field. Replace main with the body:

var m = document.getElementsByTagName("BODY")[0];

This will catch all key strokes on the page unless there are nested handlers on input fields.

The problem you encounter is because of event bubbling/trickling and input focus. The main is not "focused" upon so it doesn't get any keyboard event fired.

Body, on the contrary, is implicitly "focused" when no text field is focused and no text selection is made.

Upvotes: 2

Related Questions