Find On Page – JavaScript Snippet

It’s pretty uncommon to need this functionality with most modern browsers having find on page or search features. However, if you’re looking to include “find-on-page” functionality, you can do so by following the instructions below.

The below JavaScript will use the window.find which is supported by Google, Firefox, and Opera. It also has fall-back support for Internet Explorer.

Add the below JavaScript to the HEAD section of your website.

<script language="JavaScript">
<!--
var TRange=null;
function findString (str) {
 if (parseInt(navigator.appVersion)<4) return;
 var strFound;
 if (window.find) {
  // CODE FOR BROWSERS THAT SUPPORT window.find (Google, Firefox, Opera)
  strFound=self.find(str);
  if (!strFound) {
   strFound=self.find(str,0,1);
   while (self.find(str,0,1)) continue;
  }
 }
 else if (navigator.appName.indexOf("Microsoft")!=-1) {
  // EXPLORER-SPECIFIC CODE - IE is such a special browser...
  if (TRange!=null) {
   TRange.collapse(false);
   strFound=TRange.findText(str);
   if (strFound) TRange.select();
  }
  if (TRange==null || strFound==0) {
   TRange=self.document.body.createTextRange();
   strFound=TRange.findText(str);
   if (strFound) TRange.select();
  }
 }
 else if (navigator.appName=="Opera") {
  alert ("Opera browsers not supported, sorry...")
  return;
 }
 if (!strFound) alert ("String '"+str+"' not found!")
 return;
}
//-->
</script>

Next, you’ll want to add the search form that executes the JavaScript. This will be your front-end facing form.

<form id="f1" name="f1" action="javascript:void()" onsubmit="if(this.t1.value!=null &amp;&amp; this.t1.value!=&#39;&#39;)parent.findString(this.t1.value);return false;">
<input type="text" id="t1" name="t1" value="text" size="20">
<input type="submit" name="b1" value="Find">
</form>

Go ahead and test the script out to make sure it works! You can also download my demo code below.

Download Source   JSFiddle Source
Hello, I'm a project manager, previous business owner, web developer, home-owner, parent, and a Cleveland sports fan.

Published by

Corey Schario

Hello, I'm a project manager, previous business owner, web developer, home-owner, parent, and a Cleveland sports fan.

Leave a Reply

Your email address will not be published. Required fields are marked *