2

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 Answers2

3

Something like this:

document.body.onkeypress = function(evt) {
  var edit = document.getElementById("add");
  edit.innerHTML=edit.innerHTML + String.fromCharCode(evt.which || evt.keyCode);
}
sg.cc
  • 1,726
  • 19
  • 41
  • This will give you strange characters for keys like the ' key and they will all be in caps. – www139 Oct 07 '15 at 15:06
  • Really? I'm testing it out in my console right now, and the alphanumeric characters seem to work okay, without converting to caps. – sg.cc Oct 07 '15 at 15:08
  • That is what it has done for me in the past when I have done this; figured it would do it for you. What browser are you using? – www139 Oct 07 '15 at 15:08
  • 1
    Oh, wow you are right. It was a problem with my code; guess I learned something; thank you! – www139 Oct 07 '15 at 15:21
1

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.

kasia
  • 111
  • 4