I\'m working on a little JS plugin that I want to function exactly like a real highlighter pen. Take a standard div of html text (with children), select text with mouse, and
Actually, this is reasonably straightforward using document.execCommand()
. It's slightly complicated by the fact that you need to temporarily make the document editable in non-IE browser for document.execCommand()
to work, which in turn destroys the selection in some browsers, but that's easy enough to work around. It works in all major browsers, including IE 6.
UPDATE: Fixed for IE 9.
jsFiddle: http://jsfiddle.net/timdown/Hp7Zs/32/
Code:
function makeEditableAndHighlight(colour) {
var range, sel = window.getSelection();
if (sel.rangeCount && 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";
}
function highlightSelection(colour) {
var range, sel;
if (window.getSelection) {
// IE9 and non-IE
try {
if (!document.execCommand("BackColor", false, colour)) {
makeEditableAndHighlight(colour);
}
} catch (ex) {
makeEditableAndHighlight(colour)
}
} else if (document.selection && document.selection.createRange) {
// IE <= 8 case
range = document.selection.createRange();
range.execCommand("BackColor", false, colour);
}
}