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 can check for shift and enter key presses in the event object.
For instance, we write
textArea.onKeyPress = (e) => {
if (e.keyCode === 13 && e.shiftKey) {
e.preventDefault();
let start = e.target.selectionStart,
end = e.target.selectionEnd;
e.target.vaiue =
prevState.message.substring(0, start) +
"\n" +
prevState.message.substring(end);
} else if (e.keyCode === 13) {
e.preventDefault();
}
};
to check keyCode and shiftKey to see if shift+enter is pressed.
If it is, we call preventDefault to prevent the default behavior.
We then get the cursor’s start and end indexes with selectionStart and selectionEnd.
Then we put the new line in between the start and end with
prevState.message.substring(0, start) + "\n" + prevState.message.substring(end);
Conclusion
To detect shift+enter and generate a new line in text area with JavaScript, we can check for shift and enter key presses in the event object.