JavaScript to recolour keywords in an HTML page in realtime

Hi,

I'm a complete beginner with JavaScript, but I've found a snippet of code that does (almost) what I want.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>Highlight test</title>
<script language="JavaScript" type="text/javascript">
function HighlightText() {
var formInput = "th";
var BodyHtml = document.getElementById("bodytext").innerText;
document.getElementById("bodytext").innerHTML = BodyHtml;
var RegText = new RegExp(formInput,"g")
var StyledText = "<span class='highlighter'>" + formInput + "</span>";
BodyHtml = BodyHtml.replace(RegText,StyledText);
document.getElementById("bodytext").innerHTML = BodyHtml
}
</script>
<style>
.highlighter {
color: #cc00FF;
background-color: #ffffff
}
</style>
</head>
<body>

<input type="button" name="go" value="Go" onclick="HighlightText();">

<p> </p>

<div id="bodytext" contenteditable=true>PureBasic is a programming language based on established BASIC rules. The key features of PureBasic are portability (Windows, AmigaOS and Linux are currently fully supported), the production of very fast and highly optimized executables and, of course, the very simple BASIC syntax. PureBasic has been created for the beginner and expert alike. We have put a lot of effort into its realization to produce a fast, reliable and system friendly language.
</div>
</body>
</html>Excuse the sample paragraph - it isn't supposed to be an advert!

What this code does is, when you press the button, recolour all instances of "th" in the bodytext element. I've experimented and got it to process multiple searchstrings with different colours.

My goal is to have an editable HTML page, where the scanning is done whenever the user types text.

The problems with the above code are:

1. It erases linebreaks.

2. It is case-sensitive. I can make the search case-insensitive by changing "g" to "gi", but the replacement is not. I need it to recolour all instances of the searchstring, without changing the case.

3. You have to press the button to initiate the HighlightText function. I want that function to be called automatically whenever the text is changed.

If anyone could help me with this, I'd be very, very grateful.

Thanks for reading,
Seymour.

PS. There's no need for me to use JavaScript, necessarily. If this can be done with another method, that's fine by me.
[2783 byte] By [Seymour Clufley] at [2007-11-20 11:42:27]
# 1 Re: JavaScript to recolour keywords in an HTML page in realtime
1. It erases linebreaks.
That is because it re-writes the actual HTML. The best way would be to just alter the background color of the tag containing the text. Below is a much simpler and more efficient way of highlighting it. This will not re-write anything, just alter styles.

<script type="text/javascript">
function highlight(id){
var obj = document.getElementById(id);
obj.style.color = '#cc00ff';
obj.style.background = '#ffffff';
}
</script>

<input type="button" value="Highlight" onclick="highlight('testdiv')" />
<div id="testdiv">Put whatever text you want here.</div>

PS. There's no need for me to use JavaScript, necessarily. If this can be done with another method, that's fine by me.
JavaScript is the only client-side scripting language that is fully supported across all browsers. If you are using a web browser, JavaScript is your only option without invoking a web server.
PeejAvery at 2007-11-8 0:43:32 >
# 2 Re: JavaScript to recolour keywords in an HTML page in realtime
That is because it re-writes the actual HTML. The best way would be to just alter the background color of the tag containing the text.That's the problem. The text doesn't have any tags around it, because the text has only just been typed by the end user.

What I'm after is basically syntax highlighting. The program is a text editor, written in HTML. It works by creating an instance of IE, then making an HTML page with styles, previously written text (and any JavaScript functions), then feeding all that into the IE window.

But I'm not sure if that is important. To all intents and purposes, it's a webpage with a huge table with "contenteditable=true" set. The user types into it, and as they type, the text is scanned and if it contains any keywords, those keywords are highlighted.

I can get the host program to execute a JS function every few seconds, but it's pretty clumsy. That's why I would prefer it to be called automatically whenever the text is changed.

So as you can see, I need to use code that, as you say, "re-writes the actual HTML". And that means the linebreak problem is still an issue, so if you can think of a way round it please let me know.

Sorry if I seem anxious about this. It's because this is the fourth approach I've used to try and make this text editor, and I'm worried it's going to prove unfeasible like the other three.

JavaScript is the only client-side scripting language that is fully supported across all browsers. If you are using a web browser, JavaScript is your only option without invoking a web server.Thanks for the info, I didn't know that. But it will always be IE.
Seymour Clufley at 2007-11-8 0:44:26 >
# 3 Re: JavaScript to recolour keywords in an HTML page in realtime
If you're interested, this thread ( http://www.htmlforums.com/script-and-service-experiences/t-automatic-keyword-colouring-97052.html) describes the project more fully.
Seymour Clufley at 2007-11-8 0:45:30 >
# 4 Re: JavaScript to recolour keywords in an HTML page in realtime
That's the problem. The text doesn't have any tags around it, because the text has only just been typed by the end user.
Then you should have given an example of this in your code. The source you provided shows that it is within a tag.

So basically, you want to change the color of the text within a <textarea> tag? The background cannot be changed except for the whole tag.

it's a webpage with a huge table with "contenteditable=true" set.
Note that your page will fail any validation that you try because contenteditable is not a valid attribute of any HTML tag.

Thanks for the info, I didn't know that. But it will always be IE.
In that case, you could also use VBScript, but VBScript is IE only. JavaScript is much more versatile.
PeejAvery at 2007-11-8 0:46:28 >
# 5 Re: JavaScript to recolour keywords in an HTML page in realtime
Then you should have given an example of this in your code. The source you provided shows that it is within a tag.Sorry if I'm being unclear. The text is plain text, which is added to the HTML code which is then displayed. When the user is finished typing, the text is extracted and saved as plain text. The formatting is there purely for display purposes and will be discarded afterwards.

Due to the structure of the HTML page that I'm going for (http://www.purebasic.fr/english/viewtopic.php?t=29291), I don't know whether it would be better to enclose all the text in a tag. Boxes containing "extra" bits of text can be scattered throughout the main text.

So basically, you want to change the color of the text within a <textarea> tag? The background cannot be changed except for the whole tag.I want certain preset words to be coloured differently from the rest of the text. This process would be applied at the start (by executing the JS function from the host program), and then continuously whenever the text was changed.

Below are examples of the effect I want. In the first image, the text has been processed (ie keywords within it have been coloured), and the caret is in the middle of a keyword. In the second image, the spacebar has been pressed and, since the keyword has been split up and is no longer a keyword, it has been returned to normal colour.

http://img518.imageshack.us/img518/3128/keyworddemons2.jpg

http://img137.imageshack.us/img137/1527/keyworddemo2ln0.jpg

Note that your page will fail any validation that you try because contenteditable is not a valid attribute of any HTML tag.I don't understand. What do you mean by "validation"?

In that case, you could also use VBScript, but VBScript is IE only. JavaScript is much more versatile.Thanks, I'll look into that.
Seymour Clufley at 2007-11-8 0:47:36 >
# 6 Re: JavaScript to recolour keywords in an HTML page in realtime
I don't understand. What do you mean by "validation"?
Validation would be checking to see if they are valid HTML or XHTML files and comply with W3C's (http://www.w3.org/) web standards.

Below are examples of the effect I want.
ImageShack is blocked by my companies network. Can you attach the images instead of linking to them?

I want certain preset words to be coloured differently from the rest of the text. This process would be applied at the start (by executing the JS function from the host program), and then continuously whenever the text was changed.
Sounds to me like you could just create an array of those presets and then read through the array changing all the occurrences of a preset word to <font style="color: #cc00FF; background-color: #ffffff">preset word</font>.

Here is a small example... (haven't tested it)
<style type="text/css">
.highlighter {
color: #cc00FF;
background-color: #ffffff
}
</style>

<div id="example">Hello. My name is Paul.</div>
<input type="button" value="Highlight" onclick="highlight()" />

<script type="text/javascript">
function highlight(){
var txt = document.getElementById('example').innerHTML;
var curPreset;
var presets = ["Hello", "Paul"];
for(i = 0; i < presets.length; i++){
curPreset = presets[i];
// since replace only replaces the first occurrence
// we have to loop to find all occurrences
while(txt.search(' ' + curPreset + ' ') > -1){
txt.replace(curPreset, ' <font class="highlighter">' + curPreset + '</font> ');
}
}
}

</script>
PeejAvery at 2007-11-8 0:48:30 >
# 7 Re: JavaScript to recolour keywords in an HTML page in realtime
Validation would be checking to see if they are valid HTML or XHTML files and comply with W3C's (http://www.w3.org/) web standards.Ah. I don't think that should be a problem. That may sound callous. If it was anything else, I'd be worried, but this page is only going to be loaded by a program that knows exactly what to do with it.

ImageShack is blocked by my companies network. Can you attach the images instead of linking to them?Sure.

Sounds to me like you could just create an array of those presets and then read through the array changing all the occurrences of a preset word to <font style="color: #cc00FF; background-color: #ffffff">preset word</font>.

Here is a small example... (haven't tested it)Thankyou very much. :) I'll try this and report back.
Seymour Clufley at 2007-11-8 0:49:28 >