contenteditable selected text save and restore
Posted
by
alex
on Stack Overflow
See other posts from Stack Overflow
or by alex
Published on 2011-01-14T03:49:54Z
Indexed on
2011/01/14
3:53 UTC
Read the original article
Hit count: 307
I came across this post that shows 2 functions on how to save and restore selected text from a contenteditable div. I have the below div set as contenteditable and the 2 function from the other post. How to i use these functions to save and restore selected text.
<div style="width:300px;padding:10px;" contenteditable="true">test test test test</div>
<script>
function saveSelection() {
if (window.getSelection) {
sel = window.getSelection();
if (sel.getRangeAt && sel.rangeCount) {
return sel.getRangeAt(0);
}
} else if (document.selection && document.selection.createRange) {
return document.selection.createRange();
}
return null;
}
function restoreSelection(range) {
if (range) {
if (window.getSelection) {
sel = window.getSelection();
sel.removeAllRanges();
sel.addRange(range);
} else if (document.selection && range.select) {
range.select();
}
}
}
</script>
© Stack Overflow or respective owner