Why does your code not work?
You can't use the keyup
event on the <div>
element as you have tried to do, because JavaScript will never fire it as the div is never focused. Elements have to be focused to receive keypress events, otherwise how would the user know where their keyboard was going to type to.
What can we do about that?
One element that always "has focus" is the <body>
of the webpage (unless of course, you are using a different area of your web browser, such as bookmarking a site, navigating with the URL bar, etc).
So, we can detect the event on the body of the page, and then change the content of the div accordingly. We can detect the event using document.body.onkeyup = function(event)
, and then get change the div content using document.getElementById("change").innerHTML
, which targets that div by it's ID, and then sets it's HTML value to something new.
However, JavaScript will only send back the code of the key that was pressed (it's internal representation of the key), not the character which the key represents - (this is actually useful if you are trying to detect if a key like backspace or ctrl has been pressed). We can get this value from the event using event.keyCode
.
Thus, we will have to transform that into a string, which is the final piece of our code : String.fromCharCode(event.keyCode)
. This transforms a character code into a string.
All together, we can update the value of the div in response to a key press.
Working Example
document.body.onkeyup = function(event) {
document.getElementById("change").innerHTML = String.fromCharCode(event.keyCode);
}
<div id="change">p</div>
Notes
- You can use
onkeypress
rather that onkeyup
if you want to detect the case of letters;
- You can use
+=
rather than =
if you want to append what you have typed now to what is already in the div;
- If you want to just use a div as a place where you can type, check out contenteditable;
- If you want a list of keycodes that do not map to a string value, check out this list.