Skip to content

Instantly share code, notes, and snippets.

@jindrichsirucek
Last active January 8, 2017 19:41
Show Gist options
  • Save jindrichsirucek/fabccfe303a23f13eae96d21978dad03 to your computer and use it in GitHub Desktop.
Save jindrichsirucek/fabccfe303a23f13eae96d21978dad03 to your computer and use it in GitHub Desktop.
It highlights all words based on selection on whole html page. Im using it for online google apps script editor. its similar function to sublimetext.
// ==UserScript==
// @name Selection highliter
// @namespace http://tampermonkey.net/
// @version 0.1
// @description It highlights all words based on selection on whole html page. Im using it for online google apps script editor. its similar function to sublimetext.
// @author [email protected]
// @match https://script.google.com/macros/*
// @grant none
// ==/UserScript==
(function() {
'use strict';
var style = document.createElement('style');
style.type = 'text/css';
// style.innerHTML = '.highiltedSelectedText { background-color: lightgreen; }';
style.innerHTML = '.highiltedSelectedText { border: 1px solid; }';
document.getElementsByTagName('head')[0].appendChild(style);
function highlightWord(word) {
var xpath = "//text()[contains(., '" + word + "')]";
var texts = document.evaluate(xpath, document.body, null, XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE, null);
for (var n = 0; n < texts.snapshotLength; n++) {
var textNode = texts.snapshotItem(n);
var p = textNode.parentNode;
var a = [];
var frag = document.createDocumentFragment();
textNode.nodeValue.split(word).forEach(function(text, i) {
var node;
if (i) {
node = document.createElement('span');
// node.style.backgroundColor = 'lightgreen';
node.className = "highiltedSelectedText";
node.appendChild(document.createTextNode(word));
frag.appendChild(node);
}
if (text.length) {
frag.appendChild(document.createTextNode(text));
}
return a;
});
p.replaceChild(frag, textNode);
}
}
document.onclick = function cancelHighlitedText()
{
var higlhitedElemts = document.getElementsByClassName("highiltedSelectedText");
console.log(higlhitedElemts);
for(var i = 3; i;i--)
for(var e in higlhitedElemts)
if((higlhitedElemts[e].className))
higlhitedElemts[e].className = higlhitedElemts[e].className.replace(/highiltedSelectedText/g,"");
document.jindraSelectedWord = "";
};
document.onselect = function() { var selectedText = getSelectionText(); if(selectedText.length <= 3 || document.jindraSelectedWord == selectedText){ return;} document.jindraSelectedWord = selectedText; console.log("Selection changed: " + selectedText); highlightWord(selectedText); };
function getSelectionText() {
var text = "";
if (window.getSelection) {
text = window.getSelection().toString();
} else if (document.selection && document.selection.type != "Control") {
text = document.selection.createRange().text;
}
return text;
}
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment