You can backup the range by storing the startContainer & startOffset as well as the endContainer & endOffset. To restore, you just create a new range object and set the start and end of that range object then add it to the selection
var zss_editor = {};
// The current selection
zss_editor.currentSelection;
zss_editor.backuprange = function(){
var selection = window.getSelection();
var range = selection.getRangeAt(0);
zss_editor.currentSelection = {"startContainer": range.startContainer, "startOffset":range.startOffset,"endContainer":range.endContainer, "endOffset":range.endOffset};
}
zss_editor.restorerange = function(){
var selection = window.getSelection();
selection.removeAllRanges();
var range = document.createRange();
range.setStart(zss_editor.currentSelection.startContainer, zss_editor.currentSelection.startOffset);
range.setEnd(zss_editor.currentSelection.endContainer, zss_editor.currentSelection.endOffset);
selection.addRange(range);
console.log(range);
}
zss_editor.setTextColor = function(color) {
zss_editor.restorerange();
document.execCommand("styleWithCSS", null, true);
document.execCommand('foreColor', false, color);
document.execCommand("styleWithCSS", null, false);
}
zss_editor.setBackgroundColor = function(color) {
zss_editor.restorerange();
document.execCommand("styleWithCSS", null, true);
document.execCommand('hiliteColor', false, color);
document.execCommand("styleWithCSS", null, false);
}
$('#backup').click(function() {
zss_editor.backuprange();
});
$('#color1').click(function() {
zss_editor.setTextColor('#007AFF');
});
$('#color2').click(function() {
zss_editor.setBackgroundColor('#007AFF');
});