Javascript Highlighter

S

Simon

Newbie question:
How can I use a TextRange object to search for text, and then
highlight it?
The enclosed example works, until you dismiss the alert (done just to
show the results). I would rather the text stayed selected! I guess it
is because the TextRange object r goes out of scope? or summat?

Any ideas?

Cheers,

Simon

<HTML>
<BODY>
Leonardo da Vinci was one of the great masters of the High
Renaissance, especially in painting, sculpture, architecture,
engineering, and science.
</BODY>
<SCRIPT>
var r;
function findInPage(str) {

r = document.body.createTextRange();
var txt = r.text;

var matches = txt.toString().match(new RegExp(str, "g"));
matches = matches ? matches.length : 0;

for (i = 0; i <= matches -1; i++) {
r.findText(str);
r.select();
var sr = document.selection.createRange();
sr.pasteHTML( "<font style='background:red' id='highlightedText'>"
+ str + "</font>");
}
alert(r);
}

</script>

<Form name="search" onSubmit="findInPage(this.string.value);">
<Font size="3"><input name="string" type="text" size="15"
value="the"></font>
<input type="submit" value="Find">
</form>
</HTML>
 
S

Simon

Followed the link(s), saw some nice screen shots, but no code! Am I
missing something?

Simon
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,756
Messages
2,569,540
Members
45,024
Latest member
ARDU_PROgrammER

Latest Threads

Top