0

I try to build a user interface with draggable elements that are supposed to be dragged over HTML textareas and input fields to fill out portions of the text within.

In order to do that, I need to dynamically change the caret position within textareas and input field I am dragging over.

To set the caret (the input cursor in a textfield) I found this function

function setCaret(el, caretPos) {
      if (el != null) {
        if (el.createTextRange) {
          let range = el.createTextRange();
          range.move("character", caretPos);
          range.select();
        } else {
          if (el.selectionStart) {
            el.focus();
            el.setSelectionRange(caretPos, caretPos);
          } else el.focus();
        }
      }
    }

from this questions accepted answer

But this method just works based on the character offset of the caret.

In my use case i want to move the caret to the mouse pointers position in a textarea / input while dragging over it.

And I could not find out if/how that would be possible.

First hope gave me the existence of .caretRangeFromPoint and .caretPositionFromPoint, but I have no idea how to control the ranges and set selections in order to SET the caret within a textarea / input from my mouse coordinates.

gauguerilla
  • 675
  • 8
  • 28

0 Answers0