In an editableContent div I want the user to type something within an inline element. Therefore, when the cursor is within this inline element, and the user uses the left arrow key, the cursor should jump to position 0 WITHIN the inline element.
Here is an example:
document.querySelector("#editable").addEventListener("keydown", (e) => {
const keys = ["ArrowLeft", "ArrowRight"]
if (keys.includes(e.code)) {
// handle event
const selection = document.getSelection()
if (!selection || !selection.anchorNode) {
return
}
if (selection.anchorNode.parentElement.nodeName !== "MARK") {
return
}
e.preventDefault()
const setOffset = offset => {
const range = document.createRange()
range.collapse()
range.setStart(selection.anchorNode, offset)
selection.removeAllRanges()
selection.addRange(range)
}
if (e.code === keys[0]) {
setOffset(0)
}
if (e.code === keys[1]) {
setOffset(selection.anchorNode.textContent.length)
}
}
})
#editable {
border: 1px solid black;
padding: 10px;
}
<div id="editable" contentEditable>
Here is some <mark>text</mark> for testing!
</div>
The problem is that setOffset(0) sets the cursor before the <mark> tag and typing there makes the text appear not within the <mark> tag.
On the other side using the right arrow and setting the cursor to the last element setOffset(selection.anchorNode.textContent.length) works as expected (typing there extends the mark tag).
Is there a trick to set the cursor to position 0 within the inline element?