Created
December 16, 2017 18:59
-
-
Save ihatecsv/98c54a3691a3f192fd3a9e2b1e0114ae to your computer and use it in GitHub Desktop.
Highlight selected text matches on page (jQuery)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//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