Reputation: 129
I have a textarea with the some lines inside:
Buy groceries:
- tomato
- Onion
- 3 carrots
- greens
I decided to add a new line after onion how can I do that? I want to click after that and add a new line with ctrl + enter combination.
My current code adds a new line to the very end of the textarea:
textaAreaField.addEventListener('keypress', function(e) {
if(e.ctrlKey) {
this.value += "\n";
}
});
No jQuery pls
Upvotes: 0
Views: 3834
Reputation: 206669
Don't flop UX. Let your users use the default SHIFT + ENTER
Using ENTER to (i.e.) send a chat post - is a common "feature". Users who want/need to create a newline they already know (in such circumstance) that thay can use SHIFT+ENTER to create a newline. That's a good déjà vu UX.
So, instead of creating additional functions, just improve the one that blurs the textarea:
var textaAreaField = document.getElementById("textaAreaField");
textaAreaField.addEventListener('keydown', function(e) {
// Blur only if ENTER was not used in combo with SHIFT
if (e.keyCode === 13 && !e.shiftKey) {
this.blur();
}
});
textarea{font:14px/1.4 sans-serif; width:100%; padding: 8px; box-sizing: border-box;min-height: 160px;}
ENTER = blur textarea<br>
ENTER + SHIFT = create newline
<textarea id="textaAreaField">
tomato
Onion
3 carrots
greens</textarea>
Upvotes: 1
Reputation: 251262
Here is a live demo to show that SHIFT
+ ENTER
works out of the box: no shenanigans.
<label>Use <code>SHIFT</code> + <code>ENTER</code> to insert a line break: <br>
<textarea>
1. A
2. B
3. C
</textarea>
</label>
Upvotes: 2
Reputation: 331
If you want to use CTRL+ENTER here's a solution:
var textAreaField = document.getElementById('tb');
textAreaField.addEventListener('keydown', function(e) {
if(e.ctrlKey && e.keyCode == 13) {
var position = this.selectionEnd;
this.value = this.value.substring(0, position) + '\n' + this.value.substring(position);
this.selectionEnd = position;
}
});
<textarea id="tb"></textarea>
Upvotes: 4