Search code examples
javascripthtmlcsshighlightingundo-redo

HTML annotations (selecting, highlighting, remove format)


I am working on a cross browser web based annotation toolset, which allows the users to select any part of a web page

  • HIGHLIGHT, if you select:

john is <li>big</li> <li>dump</li>

Result

<span style="background-color: rgb(106, 168, 79)">john is</span> <li><span style="background-color: rgb(106, 168, 79)">big</span></li> <li><span style="background-color: rgb(106, 168, 79)">dump</span></li>

  • REMOVE FORMAT: if you select:

john

from

<span style="background-color: rgb(106, 168, 79)">john is</span> <li><span style="background-color: rgb(106, 168, 79)">big</span></li> <li><span style="background-color: rgb(106, 168, 79)">dump</span></li>

Result

<span style="background-color: rgb(106, 168, 79)"></span> john <span style="background-color: rgb(106, 168, 79)">is</span> <li><span style="background-color: rgb(106, 168, 79)">big</span></li> <li><span style="background-color: rgb(106, 168, 79)">dump</span></li>

  • UNDO/REDO: nice to have feature

To be able to undo and redo the actions performed

I have a partial solution for highlighting

function highlight(colour) {
var range, sel;
if (document.selection && (!window.getSelection)) {
 // IE case
    range = document.selection.createRange();  
    range.execCommand("BackColor", false, colour);  
} else if (window.getSelection) {    
// Non-IE case 
    sel = window.getSelection();
    if (sel.getRangeAt) {
        range = sel.getRangeAt(0);
    }
//without designmode=on, you can't highlight the selected html (chrome)
    document.designMode = "on";
    if (range) {
        sel.removeAllRanges();
        sel.addRange(range);
    }
    // HiliteColor avoids FF3.5 from painting the background of the whole block
    if (!document.execCommand("HiliteColor", false, colour) ) {
        document.execCommand("BackColor", false, colour);
    }
    document.designMode = "off";
} 

}

Since my requirements had much similarity with a richtext editor, I looked into the codes of ckeditor and (extensively) in google closures editor. I have given up hope in both of them because, they work in only an editable iframe. One of my requirement is that users are not allowed to change the original text but only to add there own annotations(highlight, inline notes,etc).

I would love to here all of your opinions and if possible to point me to the right direction.

--Choesang


Solution

  • I think you can still use "rich-text-editor" way (iframe), but then try to catch "onkeypress","onkeydown" and other interactive events to stop default behavior (editing the document).