By default, pressing the Enter
key in a textarea element will create a new line. However, sometimes you may want to override this behavior and only insert new lines when Shift + Enter
is pressed. This is useful in application where we use the Enter
button to submit a form but also want to give users the ability to create new lines.
Table of Contents
Preventing the Default Enter Behavior
To prevent the default Enter behavior, you can add a keydown
event listener to the textarea element. In the listener, check if the Enter key was pressed without the Shift key. If so, call preventDefault()
on the event to stop the default new line insertion.
Allowing Shift+Enter for New Lines
You likely still want to allow users to press Shift+Enter
to create new lines. So in your keydown
listener, check if both Enter and Shift were pressed together. If so, allow the default behavior of inserting a new line.
Example Code
HTML Code:
<textarea id="myTextarea"></textarea>
JavaScript Code:
const textarea = document.getElementById('myTextarea');
textarea.addEventListener('keydown', (e) => {
if(e.keyCode === 13 && !e.shiftKey) {
e.preventDefault();
}
});
Code Explanation:
- An event listener is added that will listen to any
keydown
event that occurs. - Inside the handler, we change if the pressed key is ‘Enter‘ using
e.keyCode
, the Enter Key numeric key code is13
. And usinge.shiftKey
is used to check if the Shift key is held down. Thee.shiftKey
returns a Boolean value. It will betrue
if the Shift key is pressed. - Using e.keyCode === 13 && !e.shiftKey we checked if the Enter button is pressed without the Shift key. If true, it will prevent the default new line insertion in the textarea.
This will prevent a new line on regular Enter, but allow it on Shift+Enter.
Usage Examples
Some examples of where you may want this behavior:
- Chat boxes – Send message on Enter, add line on Shift+Enter
- Inline editing – Save on Enter, new line on Shift+Enter
- Forms – Submit on Enter, new line on Shift+Enter
Summary
In summary, you can prevent the default textarea Enter behavior and only allow new lines when Shift + Enter
is pressed. This is done by calling preventDefault()
when Enter is pressed without Shift in a keydown
listener. Useful for cases where you want Enter for another action like submitting a form.