Animating Colored Ajax Comments with jQuery

by Jake Rocheleau

on June 25, 2012

in Tutorials

There are plenty of social networking websites today where you can find dynamic Ajax-based comments. This system is more usable because you don’t need to refresh the page every time you post something new. However setting up a whole database for user comments from scratch can be difficult.

In this tutorial I want to look at using jQuery just for animating custom comments. The form will submit each post anonymously and won’t save anything to a local database. The effects are only for show – but you can easily adopt the dynamic code into a system such as WordPress, vBulletin, Joomla!, or even your own custom backend.

imgborder

Building the Document

Let’s first start with the typical HTML document code. I’m using the standard HTML5 doctype and in the header I’ve included 2 specific scripts. The first is our jQuery 1.7.2 from Google’s CDN along with a custom script labeled colorcomments.js.

  <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
  <script type="text/javascript" src="colorcomments.js"></script>

Having these scripts separated and hosted in external files will leave our index.html super clean. Additionally we can include all the CSS styles from an external style.css document. But first let’s look at the typical code for building a sample comment block.

<section id="comments">
	<!-- first comment -->
	<div id="c01" class="c clearfix">
		<section class="c-author">
			<h3><a href="https://twitter.com/ericries" target="_blank">Eric Ries</a></h3>
			<span class="pubdate">June 2, 2012</span>
		</section>
		
		<section class="c-content">
			<img src="images/default-avatar.png" alt="avatar" width="80" height="80" class="ava">
			<p>Yup this is a great comment form. Gotta love DesignMag! What a handy set of code.</p>
		</section>
	</div>

The top section element contains all of our comments. Then internally each of the comm divs is given a unique comment ID and classes. I’m using clearfix to keep the avatar/username floated next to the post content. I’ve also included some very basic avatar images to stand out amongst the sea of comments.

Comment Form Display

Since we’ll be using jQuery to append comments onto the page we don’t need to setup a full form. This could be done to appease users who have JavaScript disabled. However since we aren’t connecting into a database, and there is no action script, it doesn’t matter either way.

<section id="comment-form">
	<span class="poster">Posting As: <strong>Anonymous</strong></span>
			
	<textarea name="comm" id="comm" class="textfield"></textarea>
	<button id="subber">Post Comment</button>
</section>

Each comment is submitted as anonymous pulling content from the textarea. I’ve given the button an ID of #subber so we can check when it has been pressed. With this all setup let’s quickly look over the dynamic jQuery code along with some more unique CSS properties.

Initial JavaScript

Inside the colorcomments.js I am setting up a bunch of helpful variables. The var cid is used to represent the current comment ID, 4 being the next number incrementally. I’ve also setup some date variables we can use to display the current date when each anonymous comment is published.

$(document).ready(function(){
	// setup date variables
	var thecid = 4;
	var today = new Date();
	var monthNames = [ "January", "February", "March", "April", "May", "June",
    "July", "August", "September", "October", "November", "December" ];
    
	var day   = today.getDate();
	var month = monthNames[today.getMonth()];
	var year  = today.getFullYear();
	
	// converting line breaks into 
tags function nl2br(str, is_xhtml) { var breakTag = (is_xhtml || typeof is_xhtml === 'undefined') ? '<br />' : '<br>'; return (str + '').replace(/([^>\r\n]?)(\r\n|\n\r|\r|\n)/g, '$1'+ breakTag +'$2'); }

The last function block nl2br() is a custom bit of code ported over into JavaScript. PHP has a similar function which takes all line breaks from a string and converts them into HTML
tags. This is the simplest solution so we can keep comments in the same display format.

Handling the Click Event

The last portion of JS is checking when the user clicks on a button and how to handle checking the data. I’m using the recommended jQuery .on() event handler binding to a user click event.

// attach a click event handler
$("#subber").on("click", function(){
	var textval    = $("#comm").val();
	var commwrap   = $("#comments");
	var detailspan = $("#comment-form").children(".poster");
	var errorspan  = $("#comment-form").children(".poster").children(".error");
	
	if(textval == "" || textval == " ") {
		// if there is no text then we display an error and stop the script
		// but we only append 1 'span' element
		if(errorspan.html() == null) {
			var thehtml = '<span class="error">*please enter some content!*</span>';
			detailspan.append(thehtml);
		}
	}

I have setup some variables which makes targeting DOM elements a lot easier. We need to append this new comment towards the bottom of our #comments section. If the textarea is empty when submitted then we check if there is already an error being displayed. If not then we add it onto the page so our user knows to enter some text.

If the textarea isn’t empty then we know to add this comment onto the page. I’m using the single variable name newcommhtml to append each section together. These many lines of code concatenate to build a single comment structure with the anonymous user, avatar photo, current datetime and the post content.

	else {
		// otherwise the user has added some content and we want to append the comment!
		var newcommhtml = '<div id="c0'+thecid+'" class="cnew clearfix"> <section class="c-author">';
		newcommhtml = newcommhtml + '<h3>Anonymous</h3>';
		newcommhtml = newcommhtml + '<span class="pubdate">'+month+' '+day+', '+year+'</span> </section>';
		newcommhtml = newcommhtml + '<section class="c-content">';
		newcommhtml = newcommhtml + '<img src="images/green-avatar.png" alt="avatar" width="80" height="80" class="ava">';
		newcommhtml = newcommhtml + '<p>'+nl2br(textval)+'</p> </section></div>';
		
		var thelm = "#c0"+thecid;
		commwrap.append(newcommhtml);
		$(thelm).hide().fadeIn('slow');

Immediately after appending this onto the page we hide the element and use the jQuery .fadeIn() method. This provides a neat effect instead of just plopping new HTML into the list. Also after a certain amount of time has passed we apply a new class named .green. This can be accomplished using the setTimeout() method.

		setTimeout(function() { $(thelm).addClass('green'); }, 800);
		
		$("#comm").val("");
		thecid++;
		
		if(errorspan.html() != null) {
			errorspan.remove();
		}
	}
});

This gives the effect of each new comment fading in with a yellow highlight and saving state with a bright green background. Finally in the last few lines we clear away any comment errors and leftover text inside the textarea. We also increment the comment ID count by +1 so none of the cid values will conflict.

New Comment Styles

If you noticed in the JS code we’re appending a different class to the dynamic comments. This is called .cnew and that is how we know to target the unique backgrounds. All of the gradients are built using CSS3 properties, and they should be fully compliant with all modern-day web browsers. Check out the code below:

/** comment displays **/
.c { display: block; padding-top: 15px; border-bottom: 1px solid #aaa; background: #fff; padding-bottom: 10px; }

.cnew {
background: #ebebd5;
background: -moz-linear-gradient(top,  #ebebd5 0%, #f8f8e4 100%);
background: -webkit-gradient(linear, left top, left bottom, color-stop(0%,#ebebd5), color-stop(100%,#f8f8e4));
background: -webkit-linear-gradient(top,  #ebebd5 0%,#f8f8e4 100%);
background: -o-linear-gradient(top,  #ebebd5 0%,#f8f8e4 100%);
background: -ms-linear-gradient(top,  #ebebd5 0%,#f8f8e4 100%);
background: linear-gradient(top,  #ebebd5 0%,#f8f8e4 100%);
filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#ebebd5', endColorstr='#f8f8e4',GradientType=0 );
display: block; 
padding-top: 15px; 
padding-bottom: 10px;
border-bottom: 1px solid #93a18a;
}

You can tell that the comments are displayed in mostly the same fashion. But it helps to know at a glance which comments are yours vs. other peoples. The color changes are subtle but they look really good in a working comments form.

The last interesting bit of CSS copies over many of the same gradient properties for our green effect. Right after the comment begins to fade in we put a timer on 800 milliseconds. After this time has passed we append the .green class which updates our background color.

.cnew.green {
background: #deebd7;
background: -moz-linear-gradient(top,  #deebd7 0%, #f2fbed 100%);
background: -webkit-gradient(linear, left top, left bottom, color-stop(0%,#deebd7), color-stop(100%,#f2fbed));
background: -webkit-linear-gradient(top,  #deebd7 0%,#f2fbed 100%);
background: -o-linear-gradient(top,  #deebd7 0%,#f2fbed 100%);
background: -ms-linear-gradient(top,  #deebd7 0%,#f2fbed 100%);
background: linear-gradient(top,  #deebd7 0%,#f2fbed 100%);
filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#deebd7', endColorstr='#f2fbed',GradientType=0 );
display: block; 
padding-top: 15px; 
padding-bottom: 10px;
border-bottom: 1px solid #93a18a;
}

It’s all fairly typical code if you’ve worked with CSS gradients before. We can resize and reposition the comments anywhere to still get a similar effect. Try out this demo in your own website and see if you can customize the layout to suit your own.

imgborder

Conclusion

This tutorial incorporates some unique CSS/JS techniques which can bring your comments to life. I enjoy building these custom effects because you don’t see them being utilized very often. Definitely download a copy of the source code and see what you can build off this demo. Additionally let us know any thoughts or ideas you have in the post discussion area.

Powered by Shutterstock

About Jake Rocheleau

Jake is a digital researcher and writer on many popular design magazines. He frequently writes on topics including web design, user experience, mobile apps, and project management. You can find him all throughout Google and tweeting @jakerocheleau. Connect with Jake on google+