Append keystrokes to div JS

327 Views Asked by At

I was wondering which, if any, framework would be the best to achieve capturing keystrokes and appending these to, say a "p" element. What I'm trying to achieve is having the client type something on the keyboard, and then have that sentence or whatever, appended to html, hereby displaying it in the "p" element.

Important notice; I'm not trying to call a function at a given keypress - ex. shift+alt, rather what I'm trying to do is, streaming the keyboardstrokes to an html element.

3

There are 3 best solutions below

2
On BEST ANSWER

You don't necessarily need a framework for that task.

Another possbily viable option besides Kai Christensen's would be to create a textbox outside of the visible screen area, set the focus to this textbox automatically and create a change listener for the textbox.

You can then simply replace the content of the target element with the textbox's content whenever it changes.

This saves you the trouble of listening to keyboard events manually, distinguishing upper and lower case letters etc.

0
On

Something like this?

Html

<p id="text"></p>
<input id="textinput"></input>

Js

//Register on keyup, append text from input-field to <p> element.
window.addEventListener("keyup", function () {
    document.getElementById("text").innerHTML=document.getElementById('textinput').value;
});

jsfiddle: https://jsfiddle.net/vwobq9xf/1/

0
On

I would definitely go with jQuery to capture the keys and then constantly .replace() your div with a div with the same properties that contains the latest version of the updating string. Codecademy has a great set of lessons for this type of jQuery use.

Not that I'm an expert, though. I'm sure someone else has a better answer than my own.