How to run javascript on keypress without an input field?

Viewed 3988

I'm writing a simple web site and would like to run some simple javascript when the user presses a button on their keyboard. Something as simple as running alert("Hello!"); or showing a modal box when the user presses enter would do.

After searching for a good while, I've only been able to find solutions that work if the page contains an input text field. Is it possible without it?

2 Answers

Yes, it is possible to do so, and here's how you'd do it:

document.body.addEventListener("keydown", function(event) {
    if (event.keyCode == 13) {
        alert("Hello! You pressed the enter key!");
    }
});

Yes, you can actually use eventListener for this. For example, check out this sample page.

<html>
<body>
<script>
    document.addEventListener("keypress", function(event) {
        if (event.keyCode == 13) {
            alert('You just hit enter.');
        }else if(event.keyCode ==65){
          alert('You just press A.');
        }else if(event.keyCode==97){
          alert('You just hit a.');
        }else{
          alert('You press something other than A, a and ENTER key');
            }
    })
</script>
</body>
</html>

In order to get the keycode for the various keypress you can use this:

<html>
<body>

<p>Press a key on the keyboard in the input field to get the KeyCode for that key.</p>

<input type="text" size="40" onkeypress="getKeyCode(event)">

<p id="keyCode"></p>

<script>

function getKeyCode(event) {
    var x = event.which || event.keyCode;
    document.getElementById("keyCode").innerHTML = "The keyCode is: " + x;
}
</script>

</body>
</html>

Related