Skip to content

Instantly share code, notes, and snippets.

@pbiggar
Created May 31, 2019 00:15
Show Gist options
  • Save pbiggar/ce30d8028bab49379fb51c2fe11abbca to your computer and use it in GitHub Desktop.
Save pbiggar/ce30d8028bab49379fb51c2fe11abbca to your computer and use it in GitHub Desktop.
BS-tea set cursor code
let setBrowserPos offset =
Tea.Cmd.call (fun _ ->
(* We need to set this in the new frame, as updating sets the cursor to *)
(* the start of the DOM node. *)
ignore
(Web.Window.requestAnimationFrame (fun _ -> setCursorPosition offset)) ;
() )
function setCursorPosition (pos) {
var editor = document.querySelector(".selected #fluid-editor");
if (!editor) {
console.log("no editor");
return;
}
if (pos < 0) pos = 0;
if (pos > editor.textContent.length)
pos = editor.textContent.length;
for (var i = 0; i < editor.childNodes.length; i++) {
let node = editor.childNodes[i];
let length = node.textContent.length;
if (pos <= length) {
let range = document.createRange();
range.setStart(node.childNodes[0], pos);
range.setEnd(node.childNodes[0], pos);
range.collapse(true);
let selection = document.getSelection();
selection.removeAllRanges();
selection.addRange(range);
node.focus();
return;
} else {
pos -= length;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment