I am working on improving the visual appeal of table rows. The data in table rows is generated dynamically and has lots of information. There is a column in that table which gives the time when that particular information row was issued. On the basis of the days/months etc before which the information was issued, I have to color the different rows.

It's exactly like as shown in the following link :

Moreover, the table rows must also have a small colored bar,the color of which will be determined by another field in the same row.I am wondering how to go about it in jquery. I know javascript but its getting messed up.

Any kind of help will be appreciated.


5 Years
Discussion Span
Last Post by Airshow


Develop classnames and associated CSS directives to give the various visual effects you want. Test out your CSS with hard-coded HTML.

Build your real table with :

  • <table class="highlightTable">
  • <td class="time"> (your time cell in each row)
  • <td class="aaaa"> (your other key data cell in each row)

Now start to develop your jQuery. The general format of the code will be :

	$('.highlightTable tr').each(function(){
		var $this = $(this);
		var timeValue = $this.find('td.time').html();//the value in the time cell in this row
		var aaaaValue = $this.find('td.aaaa').html();//the value some other cell in this row

By implementing the tests in functions (time_class() and sidebar_class() above), you will keep the master routine nice and clean.

Your major effort will be in developing the CSS, then in developing the javascript in time_class() and sidebar_class() . These functions should return classnames (or "") to apply the CSS directives you developed earlier.


Edited by Airshow: n/a


Thank you for the reply airshow.
Actually the problem is, I already have that table coded for by the other fellow.I have take it on from there.So basically I have to put a loop and compare the time values from the cells of each tr to the certain values,according to which the color would change.So, if you could help me with that.


It doesn't matter that the table is already developed by some other fellow. The worst case is that you will need to modify his work slightly, but maybe not depending on what he wrote.

I have given you a master javascript routine. To make it work, you need to write the subroutines time_class() and sidebar_class().

Each function must return one of several classnames and thus apply the required CSS style to each table row.

If I do the whole job for you then you will not have learned anything. Give it a try and ask specific questions when you get stuck.



That helped a lot Airshow. But since I'm a beginner.i would be thankful if you could really help me out.

function time_class() {
if (timeValue =="3 days ago") {

This is the function that i am planning to apply for all the trs. Is this sufficient. because i just need to experiment with the color changes.Nothing fancy in the start.


Kindly find the attached screenshot of the row.
thank you.

Attachments Screenshot_at_2012-01-16_13:48:04.png 192.98 KB

Is the time always in minutes or can it ever be hours/minutes or even days/hours/minutes?

If so, can you provide examples please.

Edited by Airshow: n/a


Thanks a lot for giving it a thought. But yeah the time can be from 0 minutes to 59 minutes. then it goes into hours like 17hours ago 23 hours ago and then days like, 4days ago till 30 days. and then goes into months.but the inter-conversion isnt really important.So even if I can put, say 2 color changes.just experimentation like I said.


OK, the string probably needs processing to find an actual date/time. This may be necessary because Month length varies (29/30/31 days).

However, if your color coding requirement goes to a maximum at less than a month then interpreting the sting simplifies considerably.

Another line of thought ... when the "xxxx ago" string is built (server-side), presumably it starts out as a date (in PHP, JSP, ASP or whatever). If you have access to the server-side source, then we code the original date invisibly into the HTML and avoid having to parse out the "xxxx ago" string to get back to the date. That would be ideal but clearly only possible if you control the server-side source, not if you screen-scrape.

I'm away for a few hours, will look in again when I get back.


Edited by Airshow: n/a



OK, I have found a way to do this without working out the original date/time. Simply parse the "n unit ago" string to extract n and unit, then decide on a className accordingly.

Here's the function:

//color values picked from: http://www.somacon.com/cgi/colorchart.pl
function time_class(agoString) {
	var agoValues = agoString.split(/\s+/);
	var n = Number(agoValues[0]);
	var unit = agoValues[1].toLowerCase();
		case 'm':
		case 'min':
		case 'mins':
		case 'minute':
		case 'minutes':
			clss = (n<5) ? 'minutes_A' : (n<15) ? 'minutes_B' : (n<30) ? 'minutes_C' : 'minutes_D';
		case 'h':
		case 'hr':
		case 'hrs':
		case 'hour':
		case 'hours':
			clss = (n<3) ? 'hours_A' : (n<6) ? 'hours_B' : (n<12) ? 'hours_C' : 'hours_D';
		case 'd':
		case 'day':
		case 'days':
			clss = (n<4) ? 'days_A' : (n<8) ? 'days_B' : (n<15) ? 'days_C' : 'days_D';
		case 'month':
		case 'months':
			clss = (n<3) ? 'months_A' : (n<6) ? 'months_B' : (n<12) ? 'months_C' : 'months_D';
			clss = '';
	return clss;

As you can see I have allows for some variation in the unit string (eg. m, min, mins, minute, minutes), just in case.

I tested with the following CSS :

/* color values picked from: http://www.somacon.com/cgi/colorchart.pl */
.minutes_A { background-color: #D2FFBF; }
.minutes_B { background-color: #A6FF7F; }
.minutes_C { background-color: #49EE00; }
.minutes_D { background-color: #3FCD00; }
.hours_A  { background-color: #FF9F3F; }
.hours_B  { background-color: #FF7F00; }
.hours_C  { background-color: #EE7700; }
.hours_D  { background-color: #CD6600; }
.days_A { background-color: #7FBFFF; }
.days_B { background-color: #3F9FFF; }
.days_C { background-color: #007FFF; }
.days_D { background-color: #0066CD; }
.months_A { background-color: #FF7F7F; }
.months_B { background-color: #FF3F3F; }
.months_C { background-color: #EE0000; }
.months_D { background-color: #CD0000; }

If you want to style the text rather than the background, then change background-color to color all through.

After that, the world is your oyster with regard to styles; bold, italic, letter spacing etc. etc.


Edited by Airshow: n/a


Yes I have access to the server side source.Primarily it is in jsp.Yeah, not parsing the client side html definitely saves a lot of space and makes it understandable.

I have attached 3 files.See if they are of any use.

jsp_file is in jsp format.rest all are javascript/jquery codes.

Thanks a lot.

function calculateHorizon(rc_dt, tg_dt){
	return monthDiff(new Date(rc_dt.time), new Date(tg_dt.time));

function calculateHorizonTillNow(rc_dt){
	return monthDiff(new Date(rc_dt.time), new Date())+ " ago";

function calculateHorizonFromNow(tg_dt){
	return monthDiff(new Date(), new Date(tg_dt.time));

function monthDiff(d1, d2) {
   var d1Y = d1.getFullYear();
   var d2Y = d2.getFullYear();
   var d1M = d1.getMonth();
   var d2M = d2.getMonth();
   var diff = ((d2M+12*d2Y)-(d1M+12*d1Y));	
   if(diff == 0){
	   //caculate diff in months
	   diff = dateDiff(d1, d2);
	   return diff + " days";
   }else if(diff == 1){
	   //caluculate days if less then 30 , format it in days
	    var daysDiff = Math.ceil((d2.getTime()-d1.getTime())/(3600*24000));
	    if(daysDiff < 30){
	 	   return daysDiff + " days";
	 	   return diff + " m";
	   return diff + " m";

function dateDiff(startDate, endDate) {
    //assuming days cannt be 0.
    return endDate.getDate() - startDate.getDate();

function createRecoWidget(dataObj, recoRelation, logger){
	var data = formatJson(dataObj);
	//var recoRelation = data.recoRelation;
	var recoBase = data.recoBase?data.recoBase : data.recosBase;
	var analystBase = data.analystBase;
	var stockBase = data.stockBase;
	var sectorBase = data.sectorBase;
	var context = data.context;
	var type = data.type;
	var buff = new StringBuffer();
	if(recoBase[recoRelation.id]["actn"] == 'SELL')
		buff.append('<div class="sellprocess wraper">');
	else if(recoBase[recoRelation.id]["actn"] == 'BUY')
		buff.append('<div class="buyprocess wraper">');
		buff.append('<div class="holdprocess wraper">');
		buff.append('<p class="buyprecent1 blacktext left">'+calculateRoi(getCMP(recoRelation.lstId, data.cmp), recoBase[recoRelation.id]['recoDtPx'], recoBase[recoRelation.id]['actn'])+
		'</p><p class="buyprecent2 blacktext left">'+calculateRoi(recoBase[recoRelation.id]['tgtPx'], getCMP(recoRelation.lstId, data.cmp), recoBase[recoRelation.id]['actn'])+
		'</p><p class="buyprecent3 boldtext left">'+createRecoAction(recoBase[recoRelation.id]["actn"])+
		'</p></div><div class="rupee left"><img src="'+getImgUrl('rupee-symbol.png')+'"></div><div class="buyinfo_1 left"><p class="price boldtext">'+calculatePx(recoBase[recoRelation["id"]]['recoDtPx'], true)+
		'</p><p>Reco given</p><p class="blacktext">'+calculateHorizonTillNow(recoBase[recoRelation["id"]]['recoDt'])+
		'</p></div><div class="buyinfo_2 left">'+getCMPHtml(recoRelation.lstId, data.cmp, logger, null,true)+'</div><div class="buyinfo_3 left"><p class=" greentext bigtext">'+calculatePx(recoBase[recoRelation["id"]]['tgtPx'], true)+'</p><p>Target </p><p class="blacktext">'+calculateHorizonFromNow(recoBase[recoRelation["id"]]['tgtDt'])+'</p></div>');

	return buff.toString();
<%@page import="java.util.Enumeration"%>
<%@page import="java.util.Map"%>
						<%@page import="com.mow.jsputils.JSONFilters"%>
						<%@page import="net.sf.json.JSONObject"%>
	<div class ="margint">
		Stock Recommendations by Top Analysts
                     	Map dataMap = (Map)request.getAttribute("topRatedRecosMap");
                    	String[] filarr = {"stkName", "stkCMP", "recoAction", "alysName","firmName", "indusName", "sectName", "recoHorizon"};
                    	String[] sortarr = {"recoROI", "stkName", "recoAge", "alysName","alysOARank", "recoTD"};              	
                    	JSONObject filterJsonObject =  getFilterJson(filarr, sortarr, (Map)dataMap, request);
                    	out.println(jsrenderer.render("createTable.js","getLandingFilters", filterJsonObject));

						<div id ='topRatedRecoLand_data'>

						JSONObject newRecos = JSONFilters.createJsonObject(dataMap);
						//newRecos.accumulate("page_num", 1);
						newRecos.accumulate("type", "topRatedRecoLand");
						newRecos.accumulate("cnt" , reqCountry);
						out.println( jsrenderer.render("createTable.js","createNewRecoLanding",newRecos));

								JSONObject jsonObject = new JSONObject();
								jsonObject.accumulate("page_num", request.getParameter("page"));
								jsonObject.accumulate("type", "topRatedRecoLand");
								jsonObject.accumulate("totalRows", filterJsonObject.get("totalRows"));


Let's not worry about server-side for now. If the solution in my post above at top of page 2 works, then it avoids needing to know the original date, hence avoids needing to address server-side code.

Please let me know if post at top of page 2 is any good.



Thanks a lot for the help. I will implement it and get back to you.


Hey airshow. Thanks a lot. It worked absolutely fine. But I want to implement it as a server side thing from where the date is actually coming. Could you tell me how to go about it. as this method sure works but doesnt count for the changes we might make in future.



If you want to do the whole thing server-side then, you need to build your HTML to achieve similar to what is performed client-side by my code above. ie. add a className to each <td class="time"> to give it additional style directives. Choose the stylename in accordance with the staleness of the data, eg. <td class="time staleness_X"> .

Of course, this server-side approach would provide strictly one-off styling for the page. With a little extra work, the client-side approach would allow the color coding to be "live", ie. to change colors as the data gets staler and staler without refreshing the page. Given the nature of the data, I think that would be an end-user expectation.

To facilitate that, you would need to go back to my earlier idea of encoding time-stamps in the HTML. By far the simplest encoding is a UNIX epoch representation of the time. ie, seconds since 1 January 1970. This is available in just about all server-side languages and you may well be using it already to perform date subtraction where the "xxx ago" string is computed, and/or in a database 'timestamp' field.

You can encode a time-stamp as a custom attribute of the table row or table cell to which it applies.

<tr class="..." timestamp="1326966381">...</tr>

This will be readily picked up by jQuery and converted to a javascript Date() object (which works in milliseconds rather than seconds). Here's a sample code fragment which returns a javascript Date object.

var timestamp = new Date(Number($('tr-selector').attr('timestamp')) * 1000);

You then have many Date() methods available to you for the client-side testing, manipulation and display of the timestamp.


Edited by Airshow: n/a

This article has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.