Fix and refactor getCaretPosition (#1782)

This commit is contained in:
David 2022-03-13 23:36:53 +01:00 committed by GitHub
parent c960f6488f
commit 6e05c5cd7d
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23

View file

@ -6,16 +6,21 @@ import {
// Taken from https://stackoverflow.com/a/46902361
export function getCaretPosition(node) {
var range = window.getSelection().getRangeAt(0),
preCaretRange = range.cloneRange(),
caretPosition,
tmp = document.createElement('div');
const selection = window.getSelection();
if (selection.rangeCount === 0) {
return 0;
}
const range = selection.getRangeAt(0);
const preCaretRange = range.cloneRange();
const tempElement = document.createElement('div');
preCaretRange.selectNodeContents(node);
preCaretRange.setEnd(range.endContainer, range.endOffset);
tmp.appendChild(preCaretRange.cloneContents());
caretPosition = tmp.innerHTML.length;
return caretPosition;
tempElement.appendChild(preCaretRange.cloneContents());
return tempElement.innerHTML.length;
}
// Might not need this anymore