Spread the word

Thursday, October 13, 2011

How to Color Alternate Rows in a Table with JavaScript and CSS

Tables should be used only when you are actually representing tabular data. Yes, we know that. But by default tables are not so much usable unless we put some addons and make tables usable. One of the best ways to make tabular data usable is to color alternate row backgrounds with different colors so that users don’t get lost while looking into long set of data. This not only helps users to remain on a specific track but also helps them interpret data precisely without generating much visual noise.

You can checkout the Demo of Alternate Table Row Coloring here.


Here is a very simple JavaScript script which can transform any existing tables on a page into tables with alternate row color backgrounds. This scripts check for specific class for a table on a page and puts different classes for different <tr>.
You can simply copy the following code and paste into the <head> section of your page.

function tableAlternateRow() {
    if(document.getElementsByTagName){
        var table = document.getElementById("contentsTable");
        var rows = table.getElementsByTagName("tr");
        for(i = 1; i < rows.length; i++){
            if(i % 2 == 0){
                rows[i].className = "even";
            }else{
                rows[i].className = "odd";
            }
        }
    }
}
If you just go through the function you can simply understand that this function just adds “odd” and “even” classes to every alternate <tr> of a table whose id is “contentsTable”.

Note: One thing worth noticing here is that I have started the for loop from 1 instead of 0. The reason behind this is ideally your first <tr> should be the <thead> part which should contain table headings i.e. <th>. So if you don’t have <th> in your first <tr> and you have data right from there, then you can start the for loop from 0.

Now obviously you will have to call this function as soon as the page is loaded fully. So just add this after the above code.
if (window.addEventListener) {
    window.addEventListener("load", tableAlternateRow, false);
} else if (window.attachEvent) {
    window.attachEvent("onload", tableAlternateRow);
} else {
    window.onload = tableAlternateRow;
}

So now if you see your page with Firebug, you will notice that you have a table with every alternate <tr> having the classes “odd” and “even”.

So now when you have the classes you can control their display anyway you want through CSS. So here is a sample CSS style which you can put in the header part within <style></style> tags or in your separate CSS file.
<style>
table tr.even {
    background: #fff;
}
table tr.odd {
    background: #eeeeee;
}
</style>
I prefer to keep one row background white while adding very gentle color to the other. The reason behind this is to avoid visual noise. Cause to me “less is more”. Your main information in your page is the data in the tables and not their display. Alternate row coloring or highlighting is just to help users to keep in track.

View the Demo here.

18 comments:

Bee said...

Excellent.. Thanku soo much..

Unknown said...

It stops working if i have two tables on the same page it only works on the first table.
How can i make it work on all tables on that page please ?

Anonymous said...

not working, something missing in tutorial

Anonymous said...

Awesome - exactly what I needed and it worked like a charm!

App Developers Gurgaon said...

What you're saying is completely true. I know that everybody must say the same thing, but I just think that you put it in a way that everyone can understand. I'm sure you'll reach so many people with what you've got to say.

Ariyaan said...

nice information..thanks for providing valuable information.
best web designers in hyderabad
web design services in hyderabad

Unknown said...

As stated by Stanford Medical, It's indeed the one and ONLY reason this country's women live 10 years more and weigh on average 19 kilos less than us.

(And really, it is not related to genetics or some hard exercise and EVERYTHING to do with "how" they are eating.)

BTW, I said "HOW", not "what"...

CLICK on this link to determine if this quick questionnaire can help you release your true weight loss potential

Wikisol Web Design & SEO Company said...

I read your blog such a helpful to me…… Thank you for posting
Web Designing Islamabad

Avava Ventures said...

Very good content, this is very knowledgeable for students and professionals as well.
Digital Marketing Services For Small Business
Strategic Branding Company
Brand Building Agency
Logo Design in Coimbatore

Vikas kumar said...

I have never seen this type of article post. It's amazing every topic defined deeply. Thanks for sharing it.
You can visit here for Website designing company in Delhi ncr and
Website Development company in Delhi

Nearlearn said...

Very good content, this is very knowledgeable for students and professionals as well.


Best Machine Learning Training in Bangalore

Prajjwal Arya said...

This is very helpful to everyone and it is very knowledgeable. Keep posting

madhav said...

Very nice video diwalifestival

Robtech World said...

Thank you for sharing this.
Web Designing Company In Chandigarh-Robtechworld cares about understanding you and your customers. We are here to assist you in turning your business into a huge brand.
Website Designing Company In Chandigarh

Palkin Mittal said...

Thank you for giving this useful information in this article. It's a fantastic article. I'll be waiting for your next update. I also have some useful information about the Best Website Designing Company in India, which I believe will be of great use to you.

Anonymous said...

GMCSCO is a leading global marketing company which provides low-cost digital marketing services in Bangalore, India. Digital Marketing Agency in Bangalore

Anonymous said...

Amazon Software said...

Amazon Softwares are the leading Web Designing and Digital Marketing Services in USA. With over 10+ Years of experience, Amazon Softwares has managed to become a pioneer in the field of Graphics Design, Web design, Website Designing Company in USA.

Web Designing and Digital Marketing Services in USA

Post a Comment