I'm working on a javascript library that gets the position, in pixels, of the user selection (the content they highlighted).
To pull this off, I add invisible markers to the DOM and use jQuery .position
to get the pixel location. These DOM changes cause the user selection to be lost, so I need to programmatically recreate it.
I use the rangy library to work with ranges and selections cross browser.
This is working, but there's a bug that's been eluding me for days I can't quite seem to crack. After the selection is recreated, if the user holds Shift and presses Left or Right, the selection does not grow and shrink properly in Chrome.
Fiddle showing the problem: http://jsfiddle.net/dvQ4g/3/
Highlight a portion of "This is some text" from Left to Right with the mouse.
Now, if you Shift+Right the selection expands from the right as expected.
But, if you Shift+Left, the selection DOES NOT shrink from the right as expected. Instead, it grows from the left.
(Note...if you push Shift+Left once it also changes the highlight direction, so you need to reselect to see expanding from the right work properly again.)
This is happening in Chrome, but not Firefox or Safari.
I think I've figured out why. Chrome doesn't enforce direction unless you specifically say it's backwards. Otherwise, it waits to see what the user does first. If they Shift+Right, it becomes a forwards selection. If they Shift+Left, it becomes a backwards selection. So in Chrome, programmatically creating a forwards selection isn't actually forwards at all...it's a selection that's awaiting a direction.
But knowing that, what do I do instead? I think I need to find the selection boundaries with an approach that doesn't cause the selection to be lost. Any ideas for that approach?