jQuery Comment Preview

By  on  

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() {
	var commentNode = $('#lp-comment'),
		nameNode = $('#lp-name'),
		name = $('#name'),
		website = $('#website');
	
	//comment...easy
	$('#live-preview-form input, #live-preview-form textarea').bind('blur keyup',function() {
		//comment
		commentNode.text($('#comment').val());
		commentNode.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())) {
				nameNode.html('<a href="' + website.val() + '">' + name.val() + '</a> says:');
			}
			else {
				nameNode.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!

Recent Features

Incredible Demos

Discussion

  1. Brilliant, thank you very much :)

  2. 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. I agree with the keyUp comment, but still very nice!

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

  5. Javier Martinez

    You are the best…!

  6. 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. 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. @Ben: Hard to say without seeing the page/code.

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

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

  11. Pockata

    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. very very nice! what a nice feature for the visitors. thank you for sharing!

  13. Thank’s, very nice!

  14. oh my god this is so sick!

    Man I loved that!!!

    Brilliantly awesome dude!!!

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

  16. @James Wong:

    Try changing

     $('#lp-comment').text($('#comment').val()); 
    

    To

     $('#lp-comment').html($('#comment').val());
    
  17. @Ben: Like magic! works like a charm :D ty

  18. Johnny

    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

    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=&quot;.md5( strtolower($email) ).
    "&default=".urlencode($default).
    "&size=".$size;

    echo '’;

    ?>

  20. Johnny

    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

    this now works fixed the default image php code

    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

    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. Thanx I really needed a comment box you’ve saved my life

  24. 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. 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. M

    @Ben: great

    @Rob Simpkins: great great great great great great

  27. Matt T

    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!!!

  28. Matt T

    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. Anderson

    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

  30. Donald

    @chris: u re right man

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

    .d.

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

    Regard
    Wiyono

  33. nick

    why wont this text allow you to style links and bold and italic font in the preview? is there an easy way to do that?

    • $('#lp-comment').html($('#lp-comment').html()
      	.replace(/\n/g		, '')
      	.replace(/\[b\]/g	, '').replace(/\[(\/)b\]/g		, '')
      	.replace(/\[list\]/g, '').replace(/\[(\/)list\]/g	, '')
      	.replace(/\[\*\]/g	, '').replace(/\[(\/)\*\]/g		, '_'));
      

      Sorry guy for my poor english…
      , but you do remove the “_” before and after tag ()

  34. I’m a newb to programming/coding and this is probably a stupid question to you guys… where do I paste the jquery code?

    Thanks for the help

    • danny

      test

  35. Adil Khan

    Hi david, Can you say me that how to make a comment box for my website which the people will use to post comments on my website.
    The same like which you have,
    Please Reply Soon….

    Thanks,
    Adil

  36. nadun

    hey..good post dud…but this download link is not..can you add with zip file it..i think very important all of…thank u……….

    Nadun

  37. eldante

    comments adasdasdasdasdasdasdasd

  38. alltoryburchoutlet

    I adore a couple of the articles which were written, and especially the comments posted! I will definitely be returning! The content of your post is very fresh, very worth reading

  39. Fantastic function! That’s the kind of data which are designed to end up being discussed round the internet. Shame about the look for not really placement this particular submit top! Seriously more than as well as talk to my personal website. Many thanks =)

  40. toryburchoutletsshop

    I really like your website! It’s perfectly created; I really like exactly what you’ve reached state. However you may might a bit more when it comes to content material therefore individuals might interact with this much better. cheap tory burch outlet online welcome to toryburchoutletsshop.com! Many thanks.

  41. toryburchoutletnow

    Tory burch outlet online was lucky to see your website! your website can reflect intellectual charm. Tory burch outlet online will as always watching you website. Many thanks with regard to discussing.

  42. Read a son of the building Lord, my mood is to be calm. As Lao tze have cloud: great music and sound, elephant invisible. I finally understand what I lack now is what, exactly the building Lord that kind of persist to pursue to the truth and the building Lord that kind of to ideal hard practice produce of decorous feeling.

  43. Just wanted to grant you a shout from the valley of the sun, great information. Much appreciated.

  44. ssq

    I would like to watch your article in my entire life. this article conceives outline novel, the topic has the mental strategy only, the paragraph is clear , fall the rise and fall, the main line is clear, fascinating, mild the extraordinary literature from bottom inside, is witty it may be said, a classic, is a model that my generation should the study.
    http://www.drbeatsbydre.com/

  45. I’m intersting about your content .keep up the good work.

  46. Rob Salaman

    Absolutely Fantastic, thank you!

  47. Anna

    How would add this to blogger , i need to change bloggers format, i dont no how?

  48. Mimo

    Please tell me , what is a sumbit button for this script ??

  49. i agree with you! and your suggestion is all good! i have see a lot of website, and your blog is the better one! yes!!!thanks for your share.

  50. The post is written in very a good manner and it entails much useful information for me. I am happy to find your distinguished way of writing the post.

  51. The post is written in very a good manner and it entails much useful information for me. I am happy to find your distinguished way of writing the post.

  52. michael kors handbags outlet

    Love the newest look. I enjoyed the content. Thanks for the great work.
    michael kors handbags:http://www.michaelkorsshandbagsoutlet.com/

  53. Very informative post thanks for share this with us i highly appreciate you for this information thanks once again for sharing information like this!

  54. excel

    thanks for sharing!! pretty cool and easy to understand.

  55. very very nice! Thank you <code

  56. Lorem ipsum dolor siit amet, consectetur adipkscing elit.

  57. Just desire to say your article is as surprising. The clarity in your post is simply
    excellent and i can assume you’re an expert on this subject.
    Fine with your permission allow me to grab your RSS feed to keep up to
    date with forthcoming post. Thanks a million and please keep up the enjoyable work.

  58. If you desire to take a great deal from this paragraph then you have to apply these methods to your won
    web site.

  59. Pretty nice post. I just stumbled upon your blog and wanted
    to say that I’ve truly enjoyed browsing your blog posts.

    In any case I’ll be subscribing to your rss feed and I hope you write
    again soon!

  60. Quality posts is the important to be a focus for the visitors to visit the web
    page, that’s what this website is providing.

  61. This design is steller! You definitely know how to keep a reader entertained.
    Between your wit and your videos, I was almost moved to start my own blog
    (well, almost…HaHa!) Excellent job. I really loved what you had to say, and more than that,
    how you presented it. Too cool!

Wrap your code in <pre class="{language}"></pre> tags, link to a GitHub gist, JSFiddle fiddle, or CodePen pen to embed!