javascripthtmlkeystrokes

How to capture and add keystrokes to a div element in realtime?


In the following code i'm trying to get the key presses and add it to my div element. For eg: if i'm pressing random keys such as "fhjbfwjbj" it should be added to the text in div. :

<script>
function type()
    {
        var edit = document.getElementById("add");
        edit.innerHTML=edit.innerHTML + //WHAT TO ADD?????;
    }
</script>

<body onkeypress="type()">
<div id="add" style="position:relative; left:600px; top:170px;">

Add to this text

</div>
</body>

Solution

  • Something like this:

    document.body.onkeypress = function(evt) {
      var edit = document.getElementById("add");
      edit.innerHTML=edit.innerHTML + String.fromCharCode(evt.which || evt.keyCode);
    }