How to implement
First we take the form input (e.g. "search engine keywords") and convert it into a JavaScript regular expression (e.g. "/\b(search|engine|keywords)\b/"). This regular expression will match any of the entered words where they appear in the content area of the page.
In practice what we do is generate this keywords to highlight using the search engine referer string, and also exclude common stop words such as 'is', 'and', 'are', etc, but that's another story.
Here is the code we use to call the highlighting function:
<script type="text/javascript" src="hilitor.js"></script>
<script type="text/javascript">
// global variable
var myHilitor;
document.addEventListener("DOMContentLoaded", function() {
myHilitor = new Hilitor();
myHilitor.apply("javascript highlight library");
}, false);
</script
The first line creates an instance of the
Hilitor
class, specifying that the area to be scanned is the
#content
element on the page. If we don't supply a valid element id then the script will scan
document.body
, but it's better to limit it to just your content area to avoid highlighting appearing in the page header, menu or footer.
The tag used by default to apply highlighting to matched words is the
EM
(emphasis) tag. We can change that if we want by passing a second parameter with a different tag name. You can use any tag that renders inline - so not a
DIV
or similar block element which would break the layout.
Calling the
apply
method passes the words to be highlighted to the just instantiated object which traverses the DOM inside the selected node looking for text that matches any of the keywords.
When a match is found, the text node in question is split up and a tag with style settings applied to the matching words. Each word is assigned a colour from the array supplied in the script which is then used throughout the document for that word.
To remove the highlighting from the page we simply call (from a link, script or button):
<script type="text/javascript"> myHilitor.remove(); </script>
If the colours used for highlighting look familiar, it's because they were copied from a now outdated version of Google Cache View.