Enter button pressed or not key detect by using a key event in javascript. Keycode (char code) 13 is the “Enter” key on the keyboard.
Example code Enter key event in JavaScript
HTML example code: Execute a function when the user releases a key on the keyboard and matches in if condition whether its enter key or not?
Using addEventListener with keyup
<!DOCTYPE html>
<html>
<body>
<script>
document.addEventListener("keyup", function(event) {
if (event.keyCode === 13) {
alert(event.key + event.keyCode);
}
});
</script>
</body>
</html>
Output:
Or Use onkeypress property
<input id="enterDemo" type="text" onkeypress="return
enterKeyPressed(event)" />
<script>
function enterKeyPressed(event) {
if (event.keyCode == 13) {
console.log("Enter key is pressed");
return true;
} else {
return false;
}
}
</script>
Do comment if you have any doubts or suggestions on this JS event topic.
Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version