SitePoint Sponsor |
|
User Tag List
Results 1 to 4 of 4
Thread: help with cursor positioning!
-
Aug 22, 2003, 15:30 #1
- Join Date
- Aug 2003
- Location
- CA
- Posts
- 7
- Mentioned
- 0 Post(s)
- Tagged
- 0 Thread(s)
help with cursor positioning!
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:
<html>
<script>
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;
//oCursorPos.select();
}
</script>
<body>
<div onkeyup="SyntaxHighlight()"
id="divElement" contenteditable="true" style="border:2px solid black;height:90%;width:340px;">
</div>
</body>
</html>
help is much appreciated!
-
Aug 23, 2003, 06:47 #2
- Join Date
- Mar 2002
- Location
- Lappeenranta, Finland
- Posts
- 176
- Mentioned
- 0 Post(s)
- Tagged
- 0 Thread(s)
Huh, this is a tough one, I searched for a while and did not find any good samples on createRange() usage with divs. Adding stuff inbetween there works, but manipulating the whole content and then selecting the previous place seems to be hard.
Sorry, I used an hour on this, but could not find a solution, lets hope someone with more skills can help you.
-
Aug 28, 2003, 11:50 #3
- Join Date
- Aug 2003
- Location
- CA
- Posts
- 7
- Mentioned
- 0 Post(s)
- Tagged
- 0 Thread(s)
Hmm... I wonder if it's not possible then... seems like nobody knows the answer
-
Aug 28, 2003, 12:43 #4
- Join Date
- Feb 2000
- Location
- where the World once stood
- Posts
- 700
- Mentioned
- 0 Post(s)
- Tagged
- 0 Thread(s)
Hi,
A 'possible' quick fix:Code:if (event.keyCode == 32) // code for 'space' { var strVal = strText.substring(0,5).fontcolor("red" ); strVal += strText.substring(5, strText.length).fontcolor("blue" ); document.all.divElement.innerHTML = strVal; }
If I have time, I'll come up with a better solution.
VinnyWhere the World Once Stood
the blades of grass
cut me still
Bookmarks