output in Chrome:
hey
&
This (live) example shows a short simple function, setCaretAtStartEnd
, which takes two arguments; A (editable) node to place the caret at & a Boolean indicating where to place it (start or end of the node)
const editableElm = document.querySelector('[contenteditable]');
document.querySelectorAll('button').forEach((elm, idx) =>
elm.addEventListener('click', () => {
editableElm.focus()
setCaretAtStartEnd(editableElm, idx)
})
)
function setCaretAtStartEnd( node, atEnd ){
const sel = document.getSelection();
node = node.firstChild;
if( sel.rangeCount ){
['Start', 'End'].forEach(pos =>
sel.getRangeAt(0)["set" + pos](node, atEnd ? node.length : 0)
)
}
}
[contenteditable]{ padding:5px; border:1px solid; }
Place the caret anywhere