1

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

SuperNova
  • 2,792
  • 2
  • 25
  • 34
  • Do you want to insert the cursor according to mouse coordinate? If you have set document.designMode = "on" then the cursor is set automatically when you click to edit. I also tested in WebView2 and it can work well. What problem do you encounter? – Yu Zhou Feb 23 '21 at 05:11
  • I've an external drag event and want to follow the cursor position. I can execute some javascript on mouse movement. The drag event cannot be handled by the browser directly. The WebView2 is embedded as an editor to a rich delphi application which has internal dragging functionality. – SuperNova Feb 23 '21 at 08:14

1 Answers1

1

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

SuperNova
  • 2,792
  • 2
  • 25
  • 34