JSFiddle - React, Tailwind, and code Playground
by timdown
HTML
<input type="button" onmousedown="moveCaret(); return false" value="Move caret to (100, 50)">
<div contenteditable="true" id="editor">
Dolor fatback andouille tongue pastrami. Dolor sunt veniam sirloin, speck bresaola velit jerky ham rump ut biltong meatball consequat. Pork belly exercitation ham hock shankle adipisicing shank, cow fatback brisket quis nostrud. Labore commodo veniam culpa, tongue sausage eu tail capicola magna swine. Beef ribs salami quis in ad kielbasa, in shank tenderloin officia adipisicing pancetta sunt. Dolor fatback andouille tongue pastrami. Dolor sunt veniam sirloin, speck bresaola velit jerky ham rump ut biltong meatball consequat. Pork belly exercitation ham hock shankle adipisicing shank, cow fatback brisket quis nostrud. Labore commodo veniam culpa, tongue sausage eu tail capicola magna swine. Beef ribs salami quis in ad kielbasa, in shank tenderloin officia adipisicing pancetta sunt. Dolor fatback andouille tongue pastrami. Dolor sunt veniam sirloin, speck bresaola velit jerky ham rump ut biltong meatball consequat. Pork belly exercitation ham hock shankle adipisicing shank, cow fatback brisket quis nostrud. Labore commodo veniam culpa, tongue sausage eu tail capicola magna swine. Beef ribs salami quis in ad kielbasa, in shank tenderloin officia adipisicing pancetta sunt.
</div>
JavaScript
function createCollapsedRangeFromPoint(x, y) {
var doc = document;
var position, range = null;
if (typeof doc.caretPositionFromPoint != "undefined") {
position = doc.caretPositionFromPoint(x, y);
range = doc.createRange();
range.setStart(position.offsetNode, position.offset);
range.collapse(true);
} else if (typeof doc.caretRangeFromPoint != "undefined") {
range = doc.caretRangeFromPoint(x, y);
} else if (typeof doc.body.createTextRange != "undefined") {
range = doc.body.createTextRange();
range.moveToPoint(x, y);
}
return range;
}
function moveCaret() {
var editor = document.getElementById("editor");
editor.focus();
var range = createCollapsedRangeFromPoint(100, 50);
if (range) {
if (range.select) {
// IE
range.select();
} else if (window.getSelection) {
var sel = window.getSelection();
sel.removeAllRanges();
sel.addRange(range);
}
}
}