Stupid jQuery Trick - HTML Preview

This came up in an earlier conversation today, and I don't think it's something anyone would actually use, but I love how simple it is and - well, it's kinda cool too. And stupid. (Which means it was fun to write.) So what in the heck am I talking about? Imagine you give a textarea field for your client to enter text into. You trust them with HTML, but don't want to bother with a rich text area. It would be nice to give them the ability to see their code while they type. Here's a quickie jQuery solution for this.

<script type="text/javascript" src=""></script> <script> $(document).ready(function() { $("#codehere").keyup(function() { $("#preview").html($(this).val()) }) }) </script>

code here:<br/> <textarea id="codehere" cols="50" rows="10"></textarea>


preview here: <div id="preview"></div>

Working from the bottom first - notice I've got my form (well, to be technical, it's just one field, not a complete form) and a div set up for my preview. My jQuery code then simply then binds to the form and on every key press, I set the HTML property of the preview div with the text value of the form. You can play with this here or if you just want to see what it looks like, here is a simple screen shot.

Edited at 2:39 PM: Thanks to multiple commenter for pointing out I should be using keyup instead.

Like This?

If you like this article, please consider visiting my Amazon Wishlist or donating via PayPal to show your support. You can also subscribe to the email feed to get notified of new posts.