I am trying to write a calculator in the browser, and one of the pieces of it is to highlight the syntax as the user types. I have some sample code here, which highlights the first 5 characters you type as red, and all the rest as blue (stupid test, but I couldn't come up with anything good and simple).

My problem is that the cursor position is lost. For example, type "Hello World" then click before the W to position the cursor there. Now type another character, and you will see that the cursor is moved to the end.

I have some code I commented out below which was my attempt to fix this, but it doesn't work (it highlights all the text instead).

Please note: I only care about IE 6.

here's my sample code:

function SyntaxHighlight()
var strText = document.all.divElement.innerText;
if(strText.length < 5) return;

var strVal = strText.substring(0,5).fontcolor("red");
strVal += strText.substring(5, strText.length).fontcolor("blue");

//var oCursorPos = document.selection.createRange().duplicate();
document.all.divElement.innerHTML = strVal;


<div onkeyup="SyntaxHighlight()"
id="divElement" contenteditable="true" style="border:2px solid black;height:90%;width:340px;">


help is much appreciated!