Trying to modify the text of a document onkeydown is inserting text incorrectly.

Posted by Benny on Stack Overflow See other posts from Stack Overflow or by Benny
Published on 2010-04-13T18:36:23Z Indexed on 2010/04/13 20:43 UTC
Read the original article Hit count: 315

Filed under:
|

I have the following html:

<html>
 <head>
   <script>

function myKeyDown()
{
    var myDiv = document.getElementById('myDiv');
    myDiv.innerHTML = myDiv.innerHTML.replace(/(@[a-z0-9_]+)/gi, '<strong>$1</strong>');
}

function init()
{
    document.addEventListener('keydown', myKeyDown, false);
    document.designMode = "on";
}

window.onload = init;
   </script>
 </head>
 <body>
   <div id="myDiv">
     This is my variable name: @varname. If I type here things go wrong...
   </div>
 </body>
</html>

My goal is to do a kind of syntax highlighting on edit, to highlight variable names that begin with an @ symbol. However, when I edit the document's body, the function runs but the cursor is automatically shifted to the beginning of the body before the keystroke is performed.

My hypothesis is that the keypress event is trying to insert the new character at a specified index, but when I run the replace function the indices get messed up so it defaults the character insertion point to the beginning.

I'm using Firefox to test by the way.

Any help would be appreciated.

Thanks, B.J.

© Stack Overflow or respective owner

Related posts about JavaScript

Related posts about html