The StackOverflow site does a bit more because it does syntax highlighting too, but the basic idea is to listen to the keyboard events - keydown
(better), keypress
or keyup
(not so good if a button is continuously pressed) and in its callback update the value of the target container with the value of the source container. Here's a quick example.
The best solution is to bind to both - keyup
and (keydown
or keypress
). Reason being when the key(press|down)
callbacks are fired, the value of the textbox is still the old value so when when we update the target container, it doesn't get the last character. keyup
on the other hand is fired after the value of the text box is updated. However, keyup
will not fire if you keep a button pressed as the button is only released once, so the target updates at the very end. The solution is to use both :)
$("textarea").bind('keyup keydown', function() {
$("#target").html(this.val());
});
See an example here.