Here’s a question from one of our readers, Ms. Shikha. I read your article on KeyBoardEvent.keyCode is deprecated and the alternate property .key should be used. While using the .key property, how can I detect the Shift-Enter keypress in JavaScript?
How to Detect Shift-Enter Keypress in JavaScript?
In my previous article, I had mentioned that you can use the .key property to detect if Enter key was pressed by the user using the following code.
function isKeyPressed(event) {
if(event.key === 'Enter'){
//code
}
}Now to detect Shift-Enter, you can just place another ‘if’ condition as shown below.
function isKeyPressed(event) {
if (event.key === 'Enter')
{
if(event.shiftKey)
{
console.log('shift enter was pressed');
}
}
}In the above code, shiftKey property is used to check if the user pressed ‘SHIFT’ or not. The shiftKey property returns a boolean value indicating whether or not the “SHIFT” key was pressed when a key event was triggered.
Similarly, you can use altKey, ctrlKey, metaKey properties to detect ALT, CTRL, META keys.
Here’s a guide to shiftKey property.
