Search code examples
javascriptmicrosoft-edgewebview2

Set caret to nearest possible position based on an x and y coordinate


How can I set the caret position (text cursor) to the nearest possible position based on an x and y coordinate? The whole html document has document.designMode = "on" set.

I found something to get the current X and Y coordinate, but how can I reverse the scenario?

let sel = window.getSelection();
let range = sel.getRangeAt(0);

console.log(range.getClientRects());

I'm looking for vanilla javascript that has to work in Microsoft WebView2/Edge. When dragging files onto this html document the caret position is changed exactly as I'm looking for (but I cannot use this drag operation).


Solution

  • I found the solution:

    function moveCaret(x, y) {
      let sel = window.getSelection();
      sel.removeAllRanges();
      sel.addRange(document.caretRangeFromPoint(x, y));
    }
    

    The function moves the caret to the nearest possible position. Tested on chromium browser like Opera, Edge or Chrome.

    I found a cross browser solution (after knowing the name of caretRangeFromPoint function) here on stack overflow. If you're looking for a cross browser solution please take a look here: https://stackoverflow.com/a/11191372/1635166