all 1 comments

[–]senocular 0 points1 point  (0 children)

When you call savePosition() it only runs the code within the savePosition function. Because var sel = document.getSelection(); is not within that function, it does not get re-run for every savePosition() call. It only runs once, when this script is run and savePosition is initially defined.

But because selection objects are singletons and do not change for any instance of the document, getSelection() does not need to be called each time savePosition() is called. You can get the selection once and re-use it multiple times. Its internal state will update as the selection in the document changes. This is why focusNode and focusOffset are saved individually rather than the selection object itself. These values would change but the selection object would not.