views:

176

answers:

2

My application requires heavy use of ranges (https://developer.mozilla.org/en/DOM/range). In particular, users frequently highlight text and then manipulate it. Sometimes users accidentally highlight text that includes a fragment of a word, and this produces weird results.

I'd like to be able to, given a range, check to see whether it starts or ends in the middle of a word and then, if it does, expand it so that it includes the entire word which it started / ended in the middle of.

+1  A: 

I have not worked with ranges, but it sounds like the highlight should begin immediately after a white space character and end immediately prior to a white space character. You would have to write a function that performs this check fired onmouseup event. The response to this function should be an auto-correction of the highlighting to where it should be, at the end of a word. I would also make it work at the beginning of a highlighting so that a user can click in the middle of a word and have the highlight correct to capture from the beginning of the word in order to increase accessibility to users with motion impaired interfaces. You will also want to ensure that white space characters are defined using the test method against a regex variable of:

/\s+/
+1  A: 

How about this? Kinda hacky, but I tested it in Firefox and it seemed to work. Maybe it will get you started:

function fixRange(range)
{
    var rangeString = range.toString();
    try
    {
     while (rangeString[0] != " ")
     {
      range.setStart(range.startContainer, range.startOffset - 1);
      rangeString = range.toString();
     }
     range.setStart(range.startContainer, range.startOffset + 1);
    } catch (e) {}
    try
    {
     while (rangeString[rangeString.length - 1] != " ")
     {
      range.setEnd(range.endContainer, range.endOffset + 1);
      rangeString = range.toString();
     }
     range.setEnd(range.endContainer, range.endOffset - 1);
    } catch (e) {}
    return range;
}

Example use (reselects the selected range):

var selection = window.getSelection();
selection.addRange(fixRange(selection.getRangeAt(0)));
InvisibleBacon
Horace Loeb
Yeah, I forgot to mention you would need to also check for line breaks. Maybe tabs too.Hmm.. Well feel free to post your code so far. We can take a look at it. Sounds like you might need to check for a collapsed (empty) range before running this code?
InvisibleBacon