Search code examples
javascriptjqueryonkeydownlisteners

Javascript onkeydown event on HTML element


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?


Solution

  • 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.)