Skip to content

Instantly share code, notes, and snippets.

@andsilver
Created April 27, 2020 02:41
Show Gist options
  • Save andsilver/a85b07beec748e2f49b176b683fdf217 to your computer and use it in GitHub Desktop.
Save andsilver/a85b07beec748e2f49b176b683fdf217 to your computer and use it in GitHub Desktop.
Setting Caret on contenteditable div and input box - pure javascript for crossbrowser
setSelectionRangeOnInput(el, caretPos) {
if (el.createTextRange) {
const range = el.createTextRange();
range.move('character', caretPos);
range.select();
} else {
el.focus();
if (el.selectionStart) {
el.setSelectionRange(caretPos, caretPos);
}
}
},
setSelectionRangeOnContenteditableDiv(el, start, end) {
if (document.createRange && window.getSelection) {
const range = document.createRange();
range.selectNodeContents(el);
const textNodes = this.getTextNodesIn(el);
let foundStart = false;
let charCount = 0;
let endCharCount;
for (let i = 0; i < textNodes.length; i++) {
const textNode = textNodes[i];
endCharCount = charCount + textNode.length;
if (!foundStart && start >= charCount && (start < endCharCount || (start === endCharCount && i <= textNodes.length))) {
range.setStart(textNode, start - charCount);
foundStart = true;
}
if (foundStart && end <= endCharCount) {
range.setEnd(textNode, end - charCount);
break;
}
charCount = endCharCount;
i++;
}
const sel = window.getSelection();
sel.removeAllRanges();
sel.addRange(range);
} else if (document.selection && document.body.createTextRange) {
const textRange = document.body.createTextRange();
textRange.moveToElementText(el);
textRange.collapse(true);
textRange.moveEnd('character', end);
textRange.moveStart('character', start);
textRange.select();
}
},
getTextNodesIn(node) {
const textNodes = [];
if (node.nodeType === 3) {
textNodes.push(node);
} else {
const children = node.childNodes;
for (let i = 0, len = children.length; i < len; ++i) {
textNodes.push.apply(textNodes, this.getTextNodesIn(children[i]));
}
}
return textNodes;
},
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment