Skip to content

Instantly share code, notes, and snippets.

@bpceee
Last active October 20, 2016 06:10
Show Gist options
  • Save bpceee/830d352aaa3e07b749ec76fcca055614 to your computer and use it in GitHub Desktop.
Save bpceee/830d352aaa3e07b749ec76fcca055614 to your computer and use it in GitHub Desktop.
set caret(cursor) position in contenteditable element (div)
<html>
<!-- http://jsfiddle.net/timdown/vXnCM/-->
<head>
<title>Get/Set Caret in Textarea Example</title>
<script>
function test() {
var el = document.getElementById('editable');
var range = document.createRange();
var sel = window.getSelection();
range.setStart(el.childNodes[2], 5);
range.collapse(true);
sel.removeAllRanges();
sel.addRange(range);
el.focus();
}
</script>
</head>
<body>
<div contenteditable="true" id='editable'>
text text text<br>text text text<br>text text text<br>
</div>
<button onclick="test()">test</button>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment