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

105 views Asked by At

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>
2

There are 2 answers

4
sg.cc On BEST ANSWER

Something like this:

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

Change onkeypress to onkeyup (that's just a matter of preference, though) and then your function should take in an event arg e.g. function type(evt) and the key will be in the keyCode property, i.e. evt.keyCode.