Skip to the content...

Welcome to the David Walsh Blog. I'm a MooTools, Dojo, jQuery, CSS, and PHP Web Developer located in Madison, Wisconsin, United States. Please contact me if I can make your experience on my website better.

jQuery Comment Preview

33 Responses »

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!

Discussion

  1. August 13, 2009 @ 10:59 am

    Brilliant, thank you very much :)

  2. August 13, 2009 @ 11:20 am

    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 :)

  3. August 13, 2009 @ 1:30 pm

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

  4. August 13, 2009 @ 1:35 pm

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

  5. javier martinez
    August 13, 2009 @ 2:06 pm

    You are the best…!

  6. August 13, 2009 @ 2:10 pm

    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?

  7. August 13, 2009 @ 4:11 pm

    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?

  8. August 13, 2009 @ 4:26 pm

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

  9. August 13, 2009 @ 6:38 pm

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

  10. August 13, 2009 @ 7:58 pm

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

  11. pockata
    August 14, 2009 @ 5:49 am

    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 .

  12. August 18, 2009 @ 9:33 am

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

  13. August 21, 2009 @ 9:03 am

    Thank’s, very nice!

  14. September 4, 2009 @ 12:37 pm

    oh my god this is so sick!

    Man I loved that!!!

    Brilliantly awesome dude!!!

  15. November 1, 2009 @ 8:26 am

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

  16. November 1, 2009 @ 11:07 am

    @James Wong:

    Try changing

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

    To

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

  17. November 1, 2009 @ 11:11 am

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

  18. johnny
    January 16, 2010 @ 8:37 pm

    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

  19. johnny
    January 16, 2010 @ 8:54 pm

    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 '’;

    ?>

  20. johnny
    January 16, 2010 @ 8:56 pm

    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)

  21. johnny
    January 16, 2010 @ 10:13 pm

    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:

  22. johnny
    January 16, 2010 @ 10:14 pm

    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]

  23. January 22, 2010 @ 9:39 am

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

  24. February 10, 2010 @ 10:47 am

    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”;

  25. February 22, 2010 @ 6:15 am

    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.

  26. guy
    February 22, 2010 @ 9:11 am

    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.

  27. m
    March 9, 2010 @ 1:26 pm

    @Ben: great

    @Rob Simpkins: great great great great great great

  28. matt t
    March 30, 2010 @ 3:52 am

    I have a form with three selection menus. but every time i run this script I’m have trouble getting only one selection menu to how it’s change in it’s corresponding #sum_… div

    If i change the value of the #game_time selection menu, the other two selection menus also change their value,

    How can i stop this?

    Here is my current script

    $(document).ready(function() {
    $(‘#form select, #summary’).bind(‘blur change’,function() {
    $(‘#sum_game_time’).text($(‘#game_time’).val());
    $(‘#sum_texas_game’).text($(‘#texas_game’).val());
    $(‘#sum_guests’).text($(‘#guests’).val());
    });
    });

    Thanks!!!

  29. matt t
    March 30, 2010 @ 3:52 am

    I have a form with three selection menus. but every time i run this script I’m have trouble getting only one selection menu to how it’s change in it’s corresponding #sum_… div

    If i change the value of the #game_time selection menu, the other two selection menus also change their value,

    How can i stop this?

    Here is my current script

    $(document).ready(function() {
    $(‘#form select, #summary’).bind(‘blur change’,function() {
    $(‘#sum_game_time’).text($(‘#game_time’).val());
    $(‘#sum_texas_game’).text($(‘#texas_game’).val());
    $(‘#sum_guests’).text($(‘#guests’).val());
    });
    });

    Thanks!!!

  30. anderson
    April 26, 2010 @ 11:18 am

    Hi all, am new to JQuery & i need to add comments/Post on my website am develpoing. please i can any one help me with a demo or link to get a download?

    Thanks

  31. donald
    May 12, 2010 @ 7:32 am

    @chris: u re right man

  32. June 2, 2010 @ 8:31 pm

    Just what I was looking for – thank you for sharing.

    .d.

  33. June 15, 2010 @ 7:18 am

    Is nice when is all script untul finish, and how the next script that show the comments?

    Regard
    Wiyono

Be Heard!

Share your thoughts with fellow developers of all skill levels! I want to hear from you!

Name*:
Email*:
Website:  
Wrap your code with <code> tags, f00!