holyredbeard
holyredbeard

Reputation: 21218

Reacting when user presses ENTER

I'm working on an application where it should be possible to run a function if the user presses ENTER regardless of where the focus is on the page (eg. in a textbox or on a button etc).

Below is the code i've experimented with, just to find out how to react when the user presses ENTER, but it doesn't work. What am I doing wrong? Thanks in advance!

var Capsule = {

init: function() {
    var button = document.getElementById("txtInput");
    button.focus();

    Capsule.events();
},

events: function() {
    function checkKeyboard(e) {
        if (e.keyCode == 13) {
            console.log("Pressed ENTER.");
            return false;
        }
    }
}
}

window.onload = Capsule.init;

Upvotes: 0

Views: 2329

Answers (1)

Rob W
Rob W

Reputation: 349012

You have to bind the event as well..

  • onkeydown - if you want to capture the event right after the key has pressed down.
  • onkeypress - if you want to capture each keystroke while holding the key pressed.
  • onkeyup - If you want to capture the event right after lifting the key.

Since you're using return false; (I recommend e.preventDefault(), you're probably looking for onkeydown or onkeypress. The default action cannot be prevented at onkeyup, because the default behaviour has already occurred.

Code:

events: function() {
    function checkKeyboard(e) {
        if (e.keyCode == 13) {
            console.log("Pressed ENTER.");
            return false;
        }
    }
    window.onkeypress = checkKeyboard; //Or: document.onkeypress = ..
}

Upvotes: 3

Related Questions