Created
October 18, 2021 15:39
-
-
Save mzechmeister/847937454ac40207e051847668e8bcec to your computer and use it in GitHub Desktop.
caret behaviour in contenteditable
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html> | |
<style> | |
div {background-color: #dfd} | |
span {background-color: #fbb} | |
</style> | |
<body> | |
The checking the caret behaviour in <code>contenteditable</code>. The caret is placed with an offset of 1 and then moved backwards. It is checked whether the caret is still in the current sibling (return value 0) or has entered the previous sibling (return value 5). | |
<div id="editable" contenteditable> <span id="sub">aaaaa</span>bbbbb | |
</div> | |
<p id="info"></p> | |
<script> | |
function testCaret(elem) { | |
let sel = window.getSelection() | |
let range = document.createRange() | |
range.setStart(elem, 1) | |
sel.addRange(range) | |
sel.modify('move', 'backward', "character") | |
return sel.focusOffset | |
} | |
info.innerHTML = testCaret(sub.nextSibling) | |
editable.focus() | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment