This script was inspired by a fellow VM forum member and was originally based on a find text and highlight script by Stephen Chapman of About.com:JavaScript. While Stephen’s script works, it works a little too good. In addition to finding the text on the web page, it also will find the text inside the page’s title tag, meta tags, link alt and title attributes, scripts and CSS. This has the unfortunate side-effect of injecting the CSS highlighting code into unwanted page elements, which often "breaks" the page layout. In all fairness to Stephen, his article was actually designed to show how to search a page and highlight text. It was not meant to be an actual working script. For one thing, it was designed to search and highlight preset terms and did not allow visitors to input their own search terms.
To fix the page search problems, a quick web search turned up a routine by James Padolsey in his article Find and Replace Text with Javascript. He also had written a find & highlight script that suffered the same problems as Stephen’s. After using it a while and receiving some comments on his original script, James re-wrote his find routine to limit the search to only text nodes of the HTML page. It is his script, with very minor alterations, that I have used. If you are interested in his technique, he details his methodology in his article.
The Code
To insert the find & highlight code on your SiteSpinner work page, open a code object, set the code placement to "Header" and enter the following code:
<script type='text/javascript'>
// USER PARAMETERS
var anyCase = true;
var wholeWords = false;
var errMsg = "No search terms entered";
// -- DO NOT ALTER BELOW THIS LINE --
function findAndReplace(searchText, replacement, searchNode) {
if (!searchText || typeof replacement === 'undefined') return;
var ig = '';
if (anyCase) ig = 'i';
var regex = typeof searchText === 'string' ?
new RegExp(searchText, ig+'g') : searchText,
childNodes = (searchNode || document.body).childNodes,
cnLength = childNodes.length,
excludes = 'html,head,style,title,link,meta,script,object,iframe';
while (cnLength--) {
var currentNode = childNodes[cnLength];
if (currentNode.nodeType === 1 &&
(excludes + ',').indexOf(currentNode.nodeName.toLowerCase() + ',') === -1) {
arguments.callee(searchText, replacement, currentNode);
}
if (currentNode.nodeType !== 3 || !regex.test(currentNode.data) ) {
continue;
}
var parent = currentNode.parentNode,
frag = (function() {
var html = currentNode.data.replace(regex, replacement),
wrap = document.createElement('div'),
frag = document.createDocumentFragment();
wrap.innerHTML = html;
while (wrap.firstChild) {
frag.appendChild(wrap.firstChild);
}
return frag;
})();
parent.insertBefore(frag, currentNode);
parent.removeChild(currentNode);
}
}
function doSearch(me) {
qsParm = me.terms.value;
if (qsParm == '') {
alert(errMsg);
return false;
}
qsParm = qsParm.replace(",","|");
if (wholeWords) {
qsParm = '\\b'+qsParm+'\\b';
qsParm = qsParm.replace("|","\\b|\\b");
}
findAndReplace(qsParm, function(term){ return '<span class="hi">' + term + '</span>'});
return false;
}
</script>
In the code there are three lines that are marked as user parameters. These can be modified to allow the script to handle the visitor’s entered search terms in the following manner:
|
Parameter |
Description |
|---|---|
|
anyCase |
If set to true (default), the script will ignore any case differences in the search terms; for example, the search terms Hello and hello will be treated the same.
If set to false, the text case will matter; for example, if searching for Hello, the text hello will not match. |
|
wholeWords |
If set to true (default), the script will search for text as a whole word or phrase (i.e., bracketed by space characters); for example, it will find and highlight book but not bookkeeper.
If set to false, the sequence of characters given in the search text will be highlighted on the pge; for example the search string book will find and highlight both the single word book and the sequence bookkeeper. |
|
errMsg |
This is the message that will appear if the script is executed without a search string being entered. You can change this to personalize the message. Just remember to enclose your message inside quotes. |
The CSS
When text is found on the page that matches the entered search terms, it will be wrapped within a <span> tag with a class of hi. CSS code is used to define how text using this class is displayed. To add this CSS code to your SiteSpinner work page, open a code object, set the code placement to "in CSS" and enter:
.hi {
color: red;
background-color: yellow;
font-weight: bold;
}
This CSS code will color the found text in red, set it to bold, and give it a yellow background color. If you are familiar with CSS coding, you could change or add font characteristics, such as making the font-style italic. Because SiteSpinner used strict CSS positioning code for text objects, you should not change the font nor font size as this could cause the text to extend beyond its designed boundaries. You can change the font color and background color using a standard HTML color name, hex-digit, or RGB color code.
The Search Form
The script is designed to execute from a form included on your work page. This form consists of a single text box to allow the visitor to enter the desired search terms, and a submit button to trigger script execution when clicked. The text box must be given a Name of terms. The submit button needs no special name, but remember to make this a submit button rather than the SiteSpinner default of button. On the Form tab, set the Method to POST. Leave the Action field empty since the form isn’t going to really submit anything. Instead, the find & highlight script will execute from the onsubmit event; in the On Submit code field, enter the following:
return doSearch(this);
The following figures show the form set-up (click to view larger image).
Enhancements
The demo page shows the working script being used with some random text. It also shows a few enhancements you could provide your visitors.
After text is found, it will remain highlighted until the page is refreshed (to restore the original HTML). One enhancement is to provide a link on the page to tell your visitor to do this and to provide an alternative to using the browser’s Back button. To use a text link, use a SiteSpinner text object to create the text link as you normally would, but leave the Link Type drop-down empty and in the URL field enter:
javascript:location.reload(true)
If you would like to use a form button, then after placing the button on your page, open the Form Editor to the Button tab, and in the Code field enter:
onclick="location.reload(true);"
Make sure you use a normal form Button and not a Submit or Reset. The following figure show the correct set up.
Two other enhancements shown on the demo page give the visitor the ability to choose whether to ignore case and/or use whole words during the text search. This is implemented by using checkboxes. On the demo page, I have use a checkbox for each option. When the visitor activates (checks) an option, that search filter is enabled. To use these features on your own page, add a checkbox for each option, then open the Form Editor to add the appropriate code to turn the filter on or off. For the ignore case option, enter the following in the Checkbox Code field:
onchange='anyCase=!anyCase;'
For the whole words option, enter the following in the Code field:
onchange='wholeWords=!wholeWords;'
When the checkbox is checked or unchecked, this little bit of code will switch the selected user parameters in the script between true or false, depending upon its current setting. Because the default state of these parameters is true, you must set the "Checked" option in the Form Editor to reflect the initial default true setting (refer to the following figures).






Contact the LowTechGeezer
VM User's Forum
Bruceee's Sandpit
Webmaster's Corner
Other Useful Sites