tags:

views:

49

answers:

2

Hi All,

I want to highlight the user selected Text. I cant use the JQuery Based API for Highlight since I want user specific highlight.

Here is how my code looks like.

var range = window.getSelection().getRangeAt(0);
var sel = window.getSelection();
range.setStart( sel.anchorNode, sel.anchorOffset );
range.setEnd(sel.focusNode,sel.focusOffset);
highlightSpan = document.createElement("span");
highlightSpan.setAttribute("style","background-color: yellow; ");
highlightSpan.appendChild(range.extractContents()); 
range.insertNode(highlightSpan)    

This works in normal scenarios but if I select some text in different paragraphs the extractContents API will validate the HTML returned and put additional tags to make it valid HTML. I want the exact HTML that was selected without the additional validating that javascript did.

Is there any way this can be done?

Regards, Tina

A: 

This has come up a few times:

http://stackoverflow.com/questions/2582831/highlight-the-text-of-the-dom-range-element http://stackoverflow.com/questions/1622629/javascript-highlight-selected-range-button

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
Please have a look at the next question.
Tina Agrawal
A: 

Thanks a lot. But I have one more thing. I want user specific highlights. So if I have highlighted something you are not able to see.

So we would need a way to do it server side. Please let me know is there a way through which I can add my own tags to the HTML.

I want to append something like this to the existing HTML.

 highlightSpan = document.createElement("abbr");
        highlightSpan.setAttribute("style","background-color: yellow;");
        highlightSpan.setAttribute("onmouseout","javascript:HideContentFade(\"deleteHighlight\");");
        highlightSpan.setAttribute("onmouseover","javascript:ShowHighlighter(\"deleteHighlight\",\""+id_val+"\");");   
Tina Agrawal