Reputation: 33
I am trying to make an application that moves a WebGL (three.js) camera around using WASD. But, when I use
onkeydown = function(e) { alert("a") }
and try to type in a text box on the same page, it triggers the listener. I changed the code to look like this:
var container = document.getElementById("container");
container.onkeydown = function(e) { alert("a") }
but this didn't work because HTML content hasn't loaded yet, so, I added jQuery:
var container;
$(function() {
container = document.getElementById("container");
container.onkeydown = function(e) { alert("a") }
});
Now, the listener doesn't work at all, so is it possible to make this work?
Upvotes: 3
Views: 2671
Reputation: 1679
You need to use the DOMContentLoaded
event to delay execution until after the HTML has loaded. In plain JavaScript, it will look something like this:
document.addEventListener('DOMContentLoaded', function() {
var container = document.getElementById('container');
container.addEventListener('keydown', function(e) { alert("a") });
});
With jQuery, it's pretty much the same, but a little shorter:
$(document).ready(function() {
var container = document.getElementById('container');
$(container).keydown(function(e) { alert("a") });
});
(Plus what Oriol said about tabindex
.)
Upvotes: 2
Reputation: 288120
In order to make it work, your element must be focused:
When an element is focused, key events received by the document must be targeted at that element. There may be no element focused; when no element is focused, key events received by the document must be targeted at the body element
However, in order to be able to focus the element, it must be focusable:
An element is focusable if all of the following conditions are met:
- The element's tabindex focus flag is set.
- The element is either being rendered or is a descendant of a
canvas
element that represents embedded content.- The element is not inert.
- The element is not disabled.
Usually, the problem is the lack of the tabindex focus flag. You set add it by adding a tabindex
attribute with an integral value.
Once the element is focusable, you need to focus it. There are multiple ways to do that, e.g.
.focus()
method.mousedown
event)tabindex
, the element will eventually become focused.For example:
var container = document.getElementById("container");
container.onkeydown = function(e) { alert("Key detected") }
#container { border: 3px solid red; padding: 10px; }
#container:focus { border-color: green; }
#container:after { content: "Now I'm not focused, so it won't work. Click me."; }
#container:focus:after { content: "Now I'm focused, so it will work. Press a key."; }
<div id="container" tabindex="-1"></div>
Upvotes: 1
Reputation: 160
function myFunction() {
alert("a");
}
<body>
<table>
<tr>
<td>
<input type="text" name="container" id="container" value="" onkeydown="myFunction()">
</td>
</tr>
</table>
</body>
Upvotes: 0