Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>I would argue that counting line breaks as two characters when calculating selection boundaries/cursor position is the correct approach. Fundamentally, those two characters <code>\r\n</code> are there in the text. They are present in the textarea's <code>value</code> property and they are in the value that is submitted to the server.</p> <p>The only arguments I can see for counting line breaks as one character are:</p> <ol> <li>Consistency with other browsers</li> <li>IE's <code>TextRange</code> methods consider the line breaks as one character</li> </ol> <p>I think neither is valid. Firstly, IE is already inconsistent with other browsers in counting line breaks as two characters rather than one. Secondly, IE's <code>TextRange</code> character-based methods are a little insane anyway, causing problems wherever they're used.</p> <p>I think it makes total sense to consider the selection/caret position as a position relative to the actual text in the textarea. This allows easy manipulation of the text.</p> <p>Here are two main functions. The first is the only textarea selection/caret position getting function I've seen that works correctly with all line breaks. You can find this here: <a href="https://stackoverflow.com/questions/3053542/how-to-get-the-start-and-end-points-of-selection-in-text-area/3053640#3053640">How to get the start and end points of selection in text area?</a>. Second, here's a complementary <code>setSelection</code> function:</p> <pre><code>function offsetToRangeCharacterMove(el, offset) { return offset - (el.value.slice(0, offset).split("\r\n").length - 1); } function setSelection(el, startOffset, endOffset) { var range = el.createTextRange(); var startCharMove = offsetToRangeCharacterMove(el, startOffset); range.collapse(true); if (startOffset == endOffset) { range.move("character", startCharMove); } else { range.moveEnd("character", offsetToRangeCharacterMove(el, endOffset)); range.moveStart("character", startCharMove); } range.select(); } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload