views:

71

answers:

3

Hello All,

I want to have it so when I type into a textbox (or an input field) and have whatever I am typing simultaneously appear in a div or just other place on the page?

The stackoverflow site does this when we type up a question. As we type a question, it shows whatever we are typing in a box below the textbox. Hope my question makes sense!

Thanks in advance.

+1  A: 

Good question... never thought of it before, but that functionality is cool.

I went to View Source:

There's a function attached to this page:

<script type="text/javascript">
    $(function() { 
        editorReady(1, heartbeat.answers);
    });   
</script>

The URL here contains the function "editorReady". http://sstatic.net/js/question.js?v=b05e8725a843

NinjaCat
+7  A: 

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.

Anurag
keydown will not repeat the last character.
Gert G
Good point @Gert. Maybe `keyup` is better but the problem of continuous button press still remains. Needs a better approach to solve both issues. The SO answer preview solves it quite well :)
Anurag
+2  A: 

You could use the .keydown() function to achieve this effect:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"&gt;
<html>
<head>
    <title>Test</title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"&gt;&lt;/script&gt;
    <script type="text/javascript">
    $(function() {
        $('#foo').keydown(function() {
            $('#result').text($(this).val());
        });
    });
    </script>
</head>
<body>
    <input type="text" name="foo" id="foo" />
    <div id="result"></div>
</body>
</html>
Darin Dimitrov