What do selectionStart and selectionEnd signify for textarea?

html, javascript, jquery, selection-api

Solution

`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.

Problem

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?

Original source

Related problems