views:

252

answers:

1

Hi,

I've got a script that changes the background colour of text that has been selected. However i'm encountering an issue when the text is selected across multiple elements/tags.

The code that i've got is:

var text = window.getSelection().getRangeAt(0);
var colour = document.createElement("hlight");
colour.style.backgroundColor = "Yellow";
text.surroundContents(colour);

And the error being output is:

Error: The boundary-points of a range does not meet specific requirements. =
NS_ERROR_DOM_RANGE_BAD_BOUNDARYPOINTS_ERR
Line: 7

I believe this is to do with the getRange() function though i'm not too sure how to proceed since I am a beginner at javascript.

Is there any other way I can replicate what I am trying to achieve?

Many thanks.

+1  A: 

This question has been asked today: http://stackoverflow.com/questions/2582831/highlight-the-text-of-the-dom-range-element

Here's my answer:

The following should do what you want. In non-IE browsers it turns on designMode, applies a background colour and then switches designMode off again.

function highlight(colour) {
    var range, sel;
    if (window.getSelection) {
        // Non-IE case
        sel = window.getSelection();
        if (sel.getRangeAt) {
            range = sel.getRangeAt(0);
        }
        document.designMode = "on";
        if (range) {
            sel.removeAllRanges();
            sel.addRange(range);
        }
        // Use HiliteColor since some browsers apply BackColor to the whole block
        if ( !document.execCommand("HiliteColor", false, colour) ) {
            document.execCommand("BackColor", false, colour);
        }
        document.designMode = "off";
    } else if (document.selection && document.selection.createRange) {
        // IE case
        range = document.selection.createRange();
        range.execCommand("BackColor", false, colour);
    }
}
Tim Down
Many thanks Tim, that worked perfectly and apologies for the duplication. The other thread didnt come up in my searches.
lethalbody