2

I 'de like to higlight text selected by the user and copy it over to a text box.

The latter part works great. But highlighting of the selected text fails if I try to highlight part of an already highlighted text.

Here's a JSFiddle Try selecting the text on the right box, then try to select part of your previous selection.

Any ideas?

The relevant code:

function highlightSelected() {
var selection = getSelected();
var range = selection.getRangeAt(0);
var newNode = document.createElement("span");
$(newNode).addClass('mark');
range.surroundContents(newNode);
return range;
}

Thanks !!

nrabinowitz
  • 55,314
  • 10
  • 149
  • 165
Yanin Elbi
  • 23
  • 4

1 Answers1

3

surroundContents() can only work if surrounding the entire range within a single element produces valid HTML (that definition is rather loose: see the spec for a proper definition). For example, the following range (denoted by pipes) can be surrounded using surroundContents():

<p>fo|o<i>bar</i>ba|z</p>

... while the following cannot:

<p>fo|o<i>ba|r</i>baz</p>

What your options are depends on exactly what you're trying to achieve. If you're just trying to change the background colour of the selection, you can use document.execCommand() for that. If you must add a class to the whole selection contents, you need something a little more complex, such as the class applier module of my Rangy library.

Community
  • 1
  • 1
Tim Down
  • 318,141
  • 75
  • 454
  • 536
  • Hey Tim! I ran across your Rangy lib in my searches but wasn't yet willing to use it since it has such a heavy footprint, 15KB compressed. So I was thinking that for what I'm trying to do - that's an overkill. – Yanin Elbi Jun 09 '11 at 07:20
  • Also, @TimDown: I tried the solution you linked to and the problem remains: highlighting a big segment and then trying to highlight part of it doesn't work. What am I doing wrong ? I updated the fiddle. – Yanin Elbi Jun 09 '11 at 07:24
  • 1
    Problem Solved !!!! All I had to do was to remove previous highlights on mousedown, not up. Also, I increased the size of the text element to the full size of the wrapping element to prevent mouseup not firing if the mouse is outside of the text. fiddle updated! – Yanin Elbi Jun 09 '11 at 08:12
  • 1
    your class applier for rangy rocks! – Michael L Watson Oct 30 '13 at 14:49