Skip to content

Instantly share code, notes, and snippets.

@hernamesbarbara
Created June 9, 2017 02:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hernamesbarbara/3c749b6575222238c0deb7349af9b4b6 to your computer and use it in GitHub Desktop.
Save hernamesbarbara/3c749b6575222238c0deb7349af9b4b6 to your computer and use it in GitHub Desktop.
Select me then press 'Highlight' button below.
<br>
<br>
<input type="button" value="Highlight" onclick="highlight('yellow');">
<script>
function makeEditableAndHighlight(colour) {
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 highlight(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);
}
}
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment