How to Detect Enter Keypress using JavaScript/JQuery
This tutorial shows how to detect an enter keypress on a keyboard using either plain JavaScript or JQuery.
- Plain JavaScript using the
onload
attribute of thebody
element. - We can use the JQuery
keypress
function to handle the enter keypress. - For ease of use, we can also write a custom plugin.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>How to Detect Enter Keypress using JavaScript/JQuery</title>
</head>
<body onkeypress="handleEnter(event)">
<script src="script.js"></script>
</body>
</html>
The script.js
is located in the same directory as the html page.
// detect enter keypress
$(document).keypress(function(e) {
var keycode = (e.keyCode ? e.keyCode : e.which);
if (keycode == '13') {
alert('You pressed enter! - keypress');
}
});
// write small plugin for keypress enter detection
$.fn.enterKey = function (fnc) {
return this.each(function () {
$(this).keypress(function (e) {
var keycode = (e.keyCode ? e.keyCode : e.which);
if (keycode == '13') {
fnc.call(this, e);
}
})
})
};
// use custom plugin
$(document).enterKey(function () {
alert('You pressed enter! - enterKey');
});
// handle enter plain javascript
function handleEnter(e){
var keycode = (e.keyCode ? e.keyCode : e.which);
if (keycode == '13') {
alert('You pressed enter! - plain javascript');
}
}
Demo
Download
Download it – detect-enter-keypress-javascript-jquery-example
keyCode is now deprecated. Still works on all browsers as of 2017 but at some point will likely be removed.