Skip to content

Instantly share code, notes, and snippets.

@cuibonobo
Forked from anonymous/jsbin.tedoradu.html
Created July 27, 2014 15:23
Show Gist options
  • Save cuibonobo/eed30f82b752c6cb98f2 to your computer and use it in GitHub Desktop.
Save cuibonobo/eed30f82b752c6cb98f2 to your computer and use it in GitHub Desktop.
Find text on a page similar to how browsers do it with the Find command.
<html>
<head>
</head>
<body>
<form name="f1" action=""
onSubmit="if(this.t1.value!=null && this.t1.value!='') findString(this.t1.value);return false">
<input type="text" name=t1 value="" size=20>
<input type="submit" name=b1 value="Find">
<p>This is some sample text.</p>
</form>
</body>
</html>
var TRange=null;
function findString (str) {
if (parseInt(navigator.appVersion)<4) return;
var strFound;
if (window.find) {
// CODE FOR BROWSERS THAT SUPPORT window.find
strFound=self.find(str);
if (strFound && self.getSelection && !self.getSelection().anchorNode) {
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
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;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment