Judging by the description you give, I infer that the anonymous function assigned the the option change
is called each time the user changes the color. If this is the case, then your code cannot work.
Why It Does Not Work
It cannot work because your code calls rangy.restoreSelection
multiple times with the same saved selection whereas this function can be called only once with a saved selection. This can be ascertained from the documentation:
Restores the selection from an object previously returned by rangy.saveSelection(). It removes any hidden marker elements created by that method.
(Emphasis added.) The markers are what allows the save and restore methods to work so if they are removed, then subsequent calls cannot work. This can also be ascertained by looking at the code of restoreSelection
, abbreviated here to what is relevant to this question:
function restoreSelection(savedSelection, preserveDirection) {
if (!savedSelection.restored) {
// ...
// Actual work
// ...
savedSelection.restored = true;
}
}
On first invocation savedSelection.restored
will be false and the actual work of restoring the selection will be performed. On subsequent calls on the same selection, savedSelection.restored
will be true and no work will be done.
Solution
Save the selection again after restoring it:
rangy.restoreSelection(window.textselection);
window.textselection = rangy.saveSelection();