1

Inside an editable element (e.g. <input type='text'/>, <div contenteditable="true">) when the caret is in the middle of the text, it will be moved to the start/end of the text if the up/down arrow key is pressed. I would like to know if this behavior is in some standard, as I want to write code relying on this behavior.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
SdtElectronics
  • 566
  • 4
  • 8
  • "*I want to write code relying on this behavior.*" - what exactly are you trying to do? This sounds like an [XY problem](https://meta.stackexchange.com/q/66377). But probably the answer is: no you should not rely on this, just let the user navigate the cursor and select text as their browser lets them. – Bergi Jan 02 '23 at 04:28
  • @Bergi I want to check whether the caret is on the first or the last line of the text. I've already achieved this in some hacky way, but I am not satisfied with it. If this behavior is defined it can be done more elegantly. If it is not in the standard I'd just go with the original way, but it's good to know if there is a standard for it. – SdtElectronics Jan 02 '23 at 04:36
  • That should not have anything to do with arrow keys, the caret might be placed there in any manner. Rather, [get the caret position](https://stackoverflow.com/q/3972014/1048572) and [check where it is](https://stackoverflow.com/q/58985076/1048572) [in the text](https://stackoverflow.com/q/3972014/1048572), i.e. in [which line of the text](https://stackoverflow.com/q/55604798/1048572). – Bergi Jan 02 '23 at 04:53

1 Answers1

-1

By spec, an input type=text cannot be multiline, since it can't have LF or CR characters:

The value attribute, if specified, must have a value that contains no U+000A LINE FEED (LF) or U+000D CARRIAGE RETURN (CR) characters. https://html.spec.whatwg.org/dev/input.html#text-(type=text)-state-and-search-state-(type=search)


If your goal is to know the caret position (or the selected range), you can use selectionStart and selectionEnd

document.querySelector('input').addEventListener('click', function() {
  console.log(
'is at start:', this.selectionStart === 0, '\n',
'is at end:',   this.selectionEnd === this.value.length)
})
<input type="text" value="Foo Bar" />

The only case I can think that that's not the behavior, is when the writing direction is "right to left", which is inverted.

<input type=text dir=rtl value="Right to Left">
<input type=text dir=ltr value="Left to Right">
Eric Fortis
  • 16,372
  • 6
  • 41
  • 62