Detecting enter key pressed in JavaScript
Sometimes I want to detect the Enter key press event in JavaScript.
Vanilla JS
// Listen for the enter key press.
document.body.addEventListener('keyup', function (e) {
if (e.keyCode == 13) {
// Simulate clicking on the submit button.
submitButton.click();
}
});
// Listen for the enter key press.
document.body.addEventListener('keyup', function (e) {
if (e.keyCode == 13) {
// Simulate clicking on the submit button.
triggerEvent(submitButton, 'click');
}
});
/**
* Trigger the specified event on the specified element.
* @param {Object} elem the target element.
* @param {String} event the type of the event (e.g. 'click').
*/
function triggerEvent(elem, event) {
// Create the event.
var clickEvent = new Event(event);
// Dispatch the event.
elem.dispatchEvent(clickEvent);
}
jQuery
$('body').on('keyup', function (evt) {
if (evt.keyCode == 13) {
// Simulate clicking on the submit button.
$button.trigger('click');
}
});