A fresh mix of code snippets and tutorials

Simple live comment preview with jQuery

Here is a very simple and basic live-preview for comments and contact forms.

To see how this works, create a blank HTML file and add the following code:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
	$(document).ready(function() {
			$('#comment').one("focus", function() {
				$('#comment').parent().after('<div id="preview-box"><div class="comment-by">Live Comment Preview</div><div id="live-preview"></div></div>');
			var $comment = '';
			$('#comment').keyup(function() {
			$comment = $(this).val();
			$comment = $comment.replace(/\n/g, "<br />").replace(/\n\n+/g, '<br /><br />');
			$('#live-preview').html( $comment );
<form action="post.php" method="post">
	<p><textarea name="comment" id="comment" cols="33" rows="11"></textarea></p>
	<p><input name="submit" value="Submit" type="submit" /></p>

Visit the page in a browser and type a comment to see it in action. Cheers!

★ Pro Tip:

Wizard’s SQL Recipes for WordPressSAC ProThe Tao of WordPress