Skip to content

Instantly share code, notes, and snippets.

@ihatecsv
Created December 16, 2017 18:59
Show Gist options
  • Save ihatecsv/98c54a3691a3f192fd3a9e2b1e0114ae to your computer and use it in GitHub Desktop.
Save ihatecsv/98c54a3691a3f192fd3a9e2b1e0114ae to your computer and use it in GitHub Desktop.
Highlight selected text matches on page (jQuery)
//Note:
//Requires jQuery! Also, you need to define a CSS class for .highlight
//Something like: .highlight{background-color: #ff96da;}
function getSelectionText() { //Thanks https://stackoverflow.com/a/5379408
var text = "";
if (window.getSelection) {
text = window.getSelection().toString();
} else if (document.selection && document.selection.type != "Control") {
text = document.selection.createRange().text;
}
return text;
}
$("body").click(function(){
$('.highlight').contents().unwrap();
var text = getSelectionText();
if(text != ""){
var bod = $("pre").html();
var regex = new RegExp(text, 'g');
var modBod = bod.replace(regex, "<span class='highlight'>" + text + "</span>");
$("pre").html(modBod);
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment