Sometimes, we want to detect "shift+enter" and generate a new line in text area with JavaScript.
In this article, we’ll look at how to detect "shift+enter" and generate a new line in text area with JavaScript.
How to detect "shift+enter" and generate a new line in text area with JavaScript?
To detect "shift+enter" and generate a new line in text area with JavaScript, we listen to the keypress event.
For instance, we write
const textarea = document.getElementById("description");
textarea.addEventListener("keypress", (e) => {
if (e.keyCode === 13 && !e.shiftKey) {
e.preventDefault();
}
});
to get the text area with getElementById
.
And then we call addEventListener
to listen to the keypress event.
In it, we check for the enter key is pressed by checking if keyCode
is 13.
And we check if shift key is pressed with shiftKey
.
Conclusion
To detect "shift+enter" and generate a new line in text area with JavaScript, we listen to the keypress event.