0

I am developing epub reader and i want to highlight selected text and save it during the next opening of this HTML i tried more than one method but all of them do not use index of text for example

function load(){
 window.document.designMode = "On";
 window.document.execCommand("hiliteColor", false, 'yellow');
  } 

Pls need help Thanks in advance

Ayman
  • 77
  • 11
  • 1
    http://stackoverflow.com/questions/3438524/save-highlighted-text-position-in-html-using-javascript – Victor Jun 22 '14 at 09:25
  • This answer show how to return index but how can we do highlight using index of text? – Ayman Jun 22 '14 at 10:59

1 Answers1

0

You could try Rangy. It's library that handles cross-browser selection highlighting.

With the Highlighter Module you can highlight the selected text.

However since HTML is stateless you won't be able to save it. You will have to serialize it with highlighter.serialize() and save the serialized string to a database or to a cookie.

It could look like this:

<script>
    // the highlighter object
    var highlighter;

    // function for the highlight button
    function highlightSelectedText() {
        highlighter.highlightSelection("highlight");
    }

    // function for the unhighlight button
    function removeHighlightFromSelectedText() {
        highlighter.unhighlightSelection();
    }

    window.onload = function() {
        rangy.init();

        highlighter = rangy.createHighlighter();

        highlighter.addClassApplier(rangy.createCssClassApplier("highlight", {
            ignoreWhiteSpace: true,
            tagNames: ["span", "a"]
        }));

        // load the selection
        var selectionSerialized = loadSelection();
        if (selectionSerialized) {
            highlighter.deserialize(selectionSerialized);
        }
    };

    window.onunload = saveSelection;

    function saveSelection() {
        var selectionSerialized = highlighter.serialize()

        // save "selectionSerialized" to a cookie or use 
        // a webservice to send it to the server and save it there.
    }

    function loadSelection(){
        // here you must fetch the serialized string from the cookie or
        // from your webservice and return it.
    }

</script>
<input type="button" onclick="highlightSelectedText()" 
  value="Highlight selection">
<input type="button" onclick="removeHighlightFromSelectedText()" 
  value="Remove highlights from selection">
<div> bla bla bla .... </div>

Since I don't know how you want to store the serialization string, I skipped the saving and loading parts.

Victor
  • 868
  • 8
  • 22
  • I tried the demo of this library but this is the first time to me to use java script i want to know the way of how to import the library in my java script code I am very sorry for this. – Ayman Jun 22 '14 at 16:27