O'Reilly

Comment Preview Using MooTools

By on  

Comment previewing is an awesome addition to any blog. I've seen really simple comment previewing and some really complex comment previewing. The following is a tutorial on creating very basic comment previewing using MooTools.

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>

You can set up your XHTML any way you'd like. It's important for the sake of consistency to make your preview display look as closely as possible to your real comments display.

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

Make your "preview" CSS look just like your real comments display.

The MooTools JavaScript

(function($){
	window.addEvent('domready',function(){
		//the build process
		var build = function() {
			//vars (fields) and blocks
			var lpcomment = $('lp-comment'), lpname = $('lp-name'), lpavatar = $('lp-avatar');
			var name = $('name'), email = $('email'), website = $('website'), comment = $('comment');
			
			//comment
			lpcomment.set('text',comment.value);
			lpcomment.set('html',lpcomment.get('html').replace(/\n/g,'<br />'));
			
			//name & websites
			if(website.value && (website.value).test(/http:\/\/[A-Za-z0-9\.-]{3,}\.[A-Za-z]{2}/)) {
				lpname.set('html','<a href="' + website.value + '">' + name.value + '</a> says:');
			}
			else {
				lpname.set('text',name.value + ' says:');
			}
			//gravatar
			if(email.value && (email.value).test(/^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/)) {
					var md5Email = MD5(email.value);
					lpavatar.set('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" />');
			}
		};
		//comment...easy
		$$('#live-preview-form input, #live-preview-form textarea').addEvents({
			keyup: build,
			blur: build
		});
	});
})(document.id);

The JavaScript is quite easy. Note that I'm doing very basic validation and formatting -- you may get as fancy or simple as you'd like. Also note that I'm using an MD5 function for the gravatar functionality. The MD5 function was found here.

This is as basic as it gets. You may want to implement functionality that checks for valid URLs and email addresses. You may also want to implement a regular expression that turns two line breaks into </p><p> tags. If you'd like to implement a more sophisticated system, I highly recommend using Thomas Aylott's SubtleTemplates.

Track.js Error Reporting

Upcoming Events

Recent Features

  • 6 Things You Didn&#8217;t Know About Firefox OS

    Firefox OS is all over the tech news and for good reason:  Mozilla's finally given web developers the platform that they need to create apps the way they've been creating them for years -- with CSS, HTML, and JavaScript.  Firefox OS has been rapidly improving,...

  • 9 Mind-Blowing WebGL Demos

    As much as developers now loathe Flash, we're still playing a bit of catch up to natively duplicate the animation capabilities that Adobe's old technology provided us.  Of course we have canvas, an awesome technology, one which I highlighted 9 mind-blowing demos.  Another technology available...

Incredible Demos

  • Build a Slick and Simple MooTools Accordion

    Last week I covered a smooth, subtle MooTools effect called Kwicks. Another great MooTools creation is the Accordion, which acts like...wait for it...an accordion! Now I've never been a huge Weird Al fan so this is as close to playing an accordion as...

  • Upload Photos to Flickr with PHP

    I have a bit of an obsession with uploading photos to different services thanks to Instagram. Instagram's iPhone app allows me to take photos and quickly filter them; once photo tinkering is complete, I can upload the photo to Instagram, Twitter, Facebook, and...

Discussion

  1. Looks cool! I’d have to cleanup it up 1st though.

    http://validator.w3.org/check?verbose=1&uri=http%3A%2F%2Fdavidwalsh.name%2Fdw-content%2Fmootools-live-preview.php

    Also, my auto filler didn’t work there even though it did – for the 2nd 2 fields – here.

  2. The demo doesn’t work in Chrome and it isn’t flawless in Firefox either. To bad, ’cause the concept is nice though. It’s already used in a (Dutch) social network called Hyves.

  3. What issue are you experiencing in FF Patrick?

  4. Also, this works perfectly for me in all browsers — please let me know what you believe to be flawed.

  5. In FF, when typing, I get a [object HTMLDivElement] instead of the avatar. After a while the text changes into the avatar.
    Chrome works now, but the first time it didn’t show me anything :-)

  6. Patrick: Ahh, I see what you mean. The “alt” attribute was set wrong. Fixed and no longer seen.

  7. Very cool. How about for jQuery? :D

  8. Ben: If there’s interest I can make a jQuery version.

  9. Very nice, I’ll definitely impliment this…thanks for sharing

  10. James

    I’m getting “undefined” instead of the avatar as I type, it then changes. This constantly flickers as I type in the text box which is very distracting.

  11. James: Good point — I’ve axed the “alt” all together because it’s causing the problem.

  12. Hey man. Why is it wrapped in a jQuery function?

  13. Mooer

    Merrick: See this post: http://mootools.net/blog/2009/06/22/the-dollar-safe-mode/

    It’s a simple closure.

  14. Awesome. Thanks!

  15. I ported this over to jQuery and made a few changes. You can get that code and see that post at http://thejavascriptblog.com/the-jquery-comment-previewer/

    James: One of the changes I made was how the Gravatar works. I changed the event structure a little bit and it no longer flickers and loads the Gravatar onBlur instead.

    Anyways I hope this helps someone. Good job David, I had a really good time with this.

  16. Paadt

    Please also do a jquery version!

  17. Nice script David, will you be using it on the davidwalsh.name blog? Ahhh there it is, had to scroll down a little. how about you put it before the form?

  18. This is so good

  19. I want to find a Jquery Comment System to implement in Joomla.. Is this the comment system that you are using here above??

    testing out posting now..

  20. This is very nice. I wander if it could be made to work with bbcode?
    Example: When you make a text bold with bbcode it shows bold in the preview pane.

  21. Donald

    Love this am gona use it tight now

  22. fatma

    how to make it confirmed by admin befor it preview

  23. Nice script David

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

Recently on David Walsh Blog

  • OâReilly Velocity Conference â New York

    My favorite front-end conference has always been O'Reilly's Velocity Conference because the conference series has focused on one of the most undervalued parts of client side coding:  speed.  So often we're so excited that our JavaScript works that we forget that speed, efficiency, and performance are just as important. The next Velocity...

  • Free Download: Font Bundle Featuring 17 Incredible Typefaces

    The only thing we love more than a good font, is a good free font. So we’ve combed the Web for some of our favorite free fonts, and gathered them here in a single download. You’ll find a variety of useful typefaces, from highly geometric designs...

  • OâReilly Velocity Conference â Amsterdam

    My favorite front-end conference has always been O'Reilly's Velocity Conference because the conference series has focused on one of the most undervalued parts of client side coding:  speed.  So often we're so excited that our JavaScript works that we forget that speed, efficiency, and performance are just as important. The next Velocity...

  • CanIUse Command Line

    Every front-end developer should be well acquainted with CanIUse, the website that lets you view browser support for browser features.  When people criticize my blog posts for not detailing browser support for features within the post, I tell them to check CanIUse:  always up to date, unlike...

  • Generating Alternative Stylesheets for Browsers Without @media

    If your CSS code is built with a mobile-first approach, it probably contains all the rules that make up the "desktop" view inside @media statements. That's great, but browsers that don't support media queries (IE 8 and below) will simply ignore them, ending up getting the...