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.