jQuery Comment Preview

Written by David Walsh on Thursday, August 13, 2009


I released a MooTools comment preview script yesterday and got numerous requests for a jQuery version. Ask and you shall receive! I’ll use the exact same CSS and HTML as yesterday.

The XHTML

<div id="live-preview-form" class="lp-block">
	<p>
		<strong>Your Name:</strong><br />
		<input type="text" name="name" id="name" value="" class="input" /><br /><br />
		<strong>Your Email:</strong><br />
		<input type="text" name="email" id="email" value="" class="input" /><br /><br />
		<strong>Your Website:</strong><br />
		<input type="text" name="website" id="website" value="" class="input" /><br /><br />
		<strong>Your Comment:</strong><br />
		<textarea name="comment" id="comment" class="input" rows="10"></textarea>
	</p>
</div>

<div id="live-preview-display" class="lp-block">
	<div id="lp-avatar"></div>
	<div id="lp-name"></div>
	<div id="lp-comment"></div>
</div>

The CSS

.lp-block		{ width:400px; float:left; }
.lp-block input, .lp-block textarea { width:90%; }
#live-preview-display 	{ background:#eee; padding:10px; margin-left:50px; margin-top:20px; }
#lp-name { font-weight:bold; }
#lp-avatar { float:right; margin:0 0 20px 20px; }
#lp-comment { padding-top:10px; font-style:italic; line-height:19px; }

The jQuery Javascript

$(document).ready(function() {
	//comment...easy
	$('#live-preview-form input, #live-preview-form textarea').bind('blur keyup',function() {
		//comment
		$('#lp-comment').text($('#comment').val());
		$('#lp-comment').html($('#lp-comment').html().replace(/\n/g,'<br />'));
		
		//name & websites
		if($('#name').val()) {
			if($('#website').val() && /http:\/\/[A-Za-z0-9\.-]{3,}\.[A-Za-z]{2}/.test($('#website').val())) {
				$('#lp-name').html('<a href="' + $('#website').val() + '">' + $('#name').val() + '</a> says:');
			}
			else {
				$('#lp-name').text($('#name').val() + ' says:');
			}
		}
		
		//gravatar
		if($('#email').val() && /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/.test($('#email').val())) {
				var md5Email = MD5($('#email').val());
				$('#lp-avatar').html('<img src="http://www.gravatar.com/avatar.php?gravatar_id=' + md5Email + '&size=80&rating=G&default=http%3A%2F%2Fdavidwalsh.name%2Fwp-content%2Fthemes%2Fdavid-walsh%2Fgraphics%2Fcom.jpg" alt="' + $('#lp-name').val() + '" />');
		}
	});
});

On the keypress and blur events, we validate and format the commenter’s name, avatar, website, and comments as necessary. As with yesterday’s MooTools post, the MD5 function can be found here.

Too easy!


Epic Discussion

Commenter Avatar August 13 / #
Ben says:

Brilliant, thank you very much :)

Commenter Avatar August 13 / #

I would perhaps use the keyup rather than keypress event, so that the final character you type appears without you having to move your focus away from the textarea.

Otherwise, really nice :)

Commenter Avatar August 13 / #
Todd says:

I agree with the keyUp comment, but still very nice!

David Walsh August 13 / #

Changed to keyup. I didn’t notice at first — i must type too fast.

Commenter Avatar August 13 / #
Javier Martinez says:

You are the best…!

Commenter Avatar August 13 / #
chris says:

Noticed a bit of jumping in FF, try throwing a min-height on your display div to fix that (won’t work in IE 6 of course but eh.) Great job though, post via AJAX for a next step?

Commenter Avatar August 13 / #
Ben says:

I just implimented this on my site. At first I was including the md5 function on an external file and firebug was saying that the function was undefined, however when I put it straight on the document it worked fine.

The filename was definatly correct. Would there be any other reason for this?

David Walsh August 13 / #

@Ben: Hard to say without seeing the page/code.

Commenter Avatar August 13 / #

Thanks for taking the time to port this to jQuery David, you’re the beez neez.

Commenter Avatar August 13 / #
Tom says:

holy crap that’s cool, I really need to start learning javascript.

Commenter Avatar August 14 / #
Pockata says:

It’s nice bro, but just one thing. It would be nice to use some line-breaking function, so when the word is too long it goes out of the box :) U can use this JS Wordwrap .

Commenter Avatar August 18 / #
Raphi says:

very very nice! what a nice feature for the visitors. thank you for sharing!

Commenter Avatar August 21 / #

Thank’s, very nice!

Commenter Avatar September 04 / #

oh my god this is so sick!

Man I loved that!!!

Brilliantly awesome dude!!!

Commenter Avatar November 01 / #

Is it possible to make it process HTML tags? For example TEXT would make “TEXT” appear bold?

Commenter Avatar November 01 / #
Ben says:

@James Wong:

Try changing

$(‘#lp-comment’).text($(‘#comment’).val());

To

$(‘#lp-comment’).html($(‘#comment’).val());

Commenter Avatar November 01 / #

@Ben: Like magic! works like a charm :D ty

Commenter Avatar January 16 / #
Johnny says:

i noticed that the gravatar does not work it always shows the default gravatar
any sugestions on how to fix that (i thought it might be it needs to pass the email in lowercase){i dont know jquery much so i dont know if its doing that}

i am currently trying to convert the md5 and as meny things as i can to php so can save the data in mysql and use on my site. but im a bit lost and its driving me nuts
i did get php to work with gravatar on my site.

any help would be grate to convert this to a jquery/php with save features
i did find a nifty mysql jquery routine
http://www.phpdeveloper.org/news/12003
that has the mysql routines to use for coments
so any ideas on how to incorp all this and to fix the bug of only displaying the default gravatar?

thank you in advance for any code or help you may provide

Commenter Avatar January 16 / #
Johnny says:

this is the php is has the problem of not displaying the default gravatar
go figure
<?php
$email = "dragonsworkshop@yahoo.com";
$default = "http//:davidwalsh.name/wp-content/themes/david-walsh/graphics/com.jpg";
$size = 50;

//You can construct your gravatar url with the following php code:

$grav_url = "http://www.gravatar.com/avatar.php?gravatar_id=".md5( strtolower($email) ).
"&default=".urlencode($default).
"&size=".$size;

echo '’;

?>

Commenter Avatar January 16 / #
Johnny says:

echo ‘IMG SRC=”‘.$grav_url.’” ALT=”?” BORDER=0′;
add a less then and greater then signs for image (didnt print in last post thought it was html)

Commenter Avatar January 16 / #
Johnny says:

this now works fixed the default image php code
[code]
<?php
function validate_gravatar($email) {
// Craft a potential url and test its headers
$hash = md5($email);
$uri = 'http://www.gravatar.com/avatar/' . $hash . '?d=404';
$headers = @get_headers($uri);
if (!preg_match("|200|", $headers[0])) {
$has_valid_avatar = FALSE;
} else {
$has_valid_avatar = TRUE;
}
return $has_valid_avatar;
}

$email = "11111xxxxx@yahoo.com";
$default = "http://davidwalsh.name/wp-content/themes/david-walsh/graphics/com.jpg";
$size = 50;

//You can construct your gravatar url with the following php code:

Commenter Avatar January 16 / #
Johnny says:

had to split the code(wouldn’t let me post thought i was spam)

$grav_url = “http://www.gravatar.com/avatar.php?gravatar_id=”.md5( strtolower($email) ).
“&d=”.$default.//urlencode($default).
//”&d=monsterid”.
“&size=”.$size;

if (validate_gravatar($email))
{
echo ‘IMG SRC=”http://’.$grav_url.’” ALT=”?” BORDER=0′;

}
else
{
echo ‘no gravatar found’;
echo ‘IMG SRC=”‘.$default.’” ALT=”?” BORDER=0′;
echo “org gravatar”;
echo ‘IMG SRC=”‘.$grav_url.’” ALT=”?” BORDER=0′;

}
// replace less then and greater then signs for image as needed
?>
[code]

Commenter Avatar January 22 / #
Sinfonia says:

Thanx I really needed a comment box you’ve saved my life

Commenter Avatar February 10 / #

Here’s my version, dating from the year 2005 (onkeyup=”ReloadTextDiv()” on the textarea) – short and sweet:

// live comment preview – comment body
function ReloadTextDiv() {
document.getElementById(“commentspreviewheader”).style.display=”block”;
document.getElementById(“commentspreview”).style.display=”block”;
document.getElementById(‘CommentDisplay’).innerHTML = ”+document.getElementById(‘requiredcomment’).value.replace(/(\r\n|\n)/g,”).replace(/(){2,}/gi,”)+”;
}
// by default do not show the commentsheader and preview until something is typed in either name or text
document.getElementById(“commentspreviewheader”).style.display=”none”;
document.getElementById(“commentspreview”).style.display=”none”;

Commenter Avatar February 22 / #

Hello,

More than 15 characters (And stop at 255 characters) long when I want to run. But it did not work. Please help me,

$(‘#commentsForm textarea’).bind(‘blur keyup’,function() {
if($(‘#comment’).length > 15){
$(‘#lp-comment’).text($(‘#comment’).val());
$(‘#lp-comment’).html($(‘#lp-comment’).html().replace(/\n/g,”));
}
});

Sincerely,
Samet ARAS.

Commenter Avatar February 22 / #
guy says:

hi. looks really fabulous. may we ask for the workfiles with whatever essential plug-ins ? throw in the database steps as well for the form? thanks a million.

Commenter Avatar March 09 / #
M says:

@Ben: great

@Rob Simpkins: great great great great great great

Be Heard!

I want to hear what you have to say! Share your comments and questions below.

Name*:
Email*:
Website:  


© David Walsh 2007-2010. Contact David Walsh. Powered by the remarkable MooTools javascript framework.