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;
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 recommende.preventDefault(), you’re probably looking foronkeydownoronkeypress. The default action cannot be prevented atonkeyup, because the default behaviour has already occurred.Code: