0

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?

Colin
  • 2,814
  • 5
  • 27
  • 37
  • In most situations you can get the pixel coordinates of the selection without having to insert anything into the DOM, if the selection is not collapsed. See http://stackoverflow.com/questions/8456652/how-to-get-the-pixel-offset-from-the-current-caret-position-in-an-iframe-with-co, http://stackoverflow.com/questions/6846230/javascript-text-selection-page-coordinates – Tim Down Jun 04 '13 at 09:01
  • From the man himself...thanks for all your work on this stuff. I feel like I've read every other one of your SO answers. It looks like there are a bunch of cross-browser issues with getting coordinates of a collapsed range. Do you think I'll be better off "collapsing" to a width of one character, instead of zero characters? e.g. You highlight "some text" - then I create a range that wraps just "s" and get the rect around that? Thanks! – Colin Jun 04 '13 at 14:50
  • Creating a range containing one character sounds good to me: it should be a lot more relaible than using a collapsed range. – Tim Down Jun 05 '13 at 10:08

0 Answers0