4

I am trying to store the value of window.getSelection(), but this value seems to change if the user selects another selection.

In my code below, I have stored the initial user's selection. I then create my form (which takes a bit of time), and when the form is finished being created I fill in the form with the user's selection. Now during the time when the form is being created, the user may select some other text, and now the object stored in my selection variable has changed. How would I prevent the value of selection from being changed?

var selection = window.getSelection();

createForm(function() {
    fillInForm(selection);
});

EDIT - I need to keep the DOM structure of the selection as the form references the position of the selected text.

Jon
  • 8,205
  • 25
  • 87
  • 146
  • can you put some more of your code? there may be a way adding a closure, but depends on the rest of your code – Guumaster Mar 10 '12 at 21:09

1 Answers1

2

The getSelection function returns a Selection object. There can only be one selection object per document, so the range associated with the selection must change if the user makes a new selection.

The user agent should allow the user to change the active document's selection. If the user makes any modification to a selection, the user agent must create a new range with suitable start and end and associate the selection with this new range (not modify the existing range).

[...]

If the user changes the selection or a script calls addRange(), the selection must be associated with a new range object, as required elsewhere in this specification.

http://dvcs.w3.org/hg/editing/raw-file/tip/editing.html#selections

Community
  • 1
  • 1
Dagg Nabbit
  • 75,346
  • 19
  • 113
  • 141
  • 2
    In other words, if the user agent selects another range, my original selection variable will now hold this new range? How am I able to preserve my original selection? I have thought of creating a temp range just to hold the original data, but won't it get overridden once the selection changes again? – Jon Mar 10 '12 at 20:40
  • @icu222much I'm not really sure... you could serialize it to a string or try "cloning" it with `Object.create` – Dagg Nabbit Mar 10 '12 at 21:03
  • @Jon https://developer.mozilla.org/en-US/docs/Web/API/Range/cloneRange solves this problem. – Bennet Huber Jan 14 '22 at 08:04