I came across following code snippet to insert enter into the the text in a textarea where ctrl + enter is pressed.
$("#txtChatMessage").keydown(MessageTextOnKeyEnter);
function MessageTextOnKeyEnter(e) {
console.log(this.selectionEnd);
if (e.keyCode == 13) {
if (e.ctrlKey) {
var val = this.value;
if (typeof this.selectionStart == "number" && typeof this.selectionEnd == "number") {
var start = this.selectionStart;
this.value = val.slice(0, start) + "\n" + val.slice(this.selectionEnd);
this.selectionStart = this.selectionEnd = start + 1;
} else if (document.selection && document.selection.createRange) {
this.focus();
var range = document.selection.createRange();
range.text = "\r\n";
range.collapse(false);
range.select();
}
}
return false;
}
}
What I don't understand is what do selectionStart and selectionEnd mean here ? According to documentation that I read, selectionStart-End contain the start-end of selected text in the input element. However, here no text is explicitly selected. On doing console.log I could see that both these properties always have some value even when the text is not selected. Why is that?
selectionStart
specifies the index of the selection/highlighted text within the <textarea>
. Similarly, selectionEnd
specifies the index where the selection ends. Initially, they are set to 0
, and if the <textarea>
is focused but no text is selected, the selectionStart
and selectionEnd
values will be the same, and reflect the position of the caret within the value of the <textarea>
. On un-focus or blur
of the <textarea>
, they will remain at the last value that they were set to before the blur
event.
Here's a fiddle you can play with: http://jsfiddle.net/5vd8pxct/
The if
block in question appears to handle cross-browser compatibility. document.selection
is for IE. selectionStart
and selectionEnd
seem to work elsewhere. I don't have IE on my machine to experiment with it, and I'm using Chrome. It appears from my fiddle that the default start/end are 0
when the page loads. If you click into/select in the box, the start end will be as expected. If you click outside the box, the positions within the box are remembered.
document.selection
is undefined in Chrome.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With