Detect Enter Key Press Using JavaScript

You can Detect Enter Key Press Using JavaScript with the help of keyCode property or KeyboardEvent which Property.

keyCode property

keyCode property returns the unicode value of the key that has triggered the onkeypress, onkeydown or onkeyup event.

Firefox browser doesn't support keyCode property, so we can use which property for it.

KeyboardEvent which Property

KeyboardEvent which Property also returns the unicode of the key pressed just like the keyCode property.

IE8 and earlier versions of Internet Explorer don't support which property so we can use keyCode property for them.

We can use both keyCode and which property simultaneously so that the code runs on all types of browsers, see the code below.

Code

<script>
document.addEventListener("keydown", function(){
var x=event.keyCode || event.which;
if(x==13)
{
alert ("Enter Key is Pressed");
}
})
</script>

Demo

Press Enter Key

Video Tutorial

Watch video tutorial on how to Detect Enter Key Press Using JavaScript.