HOW TO: Alternate Row Colours in Wordpress, using jQuery
On one of my other blogs, I wanted to give each comment an alternate row colour so that each comment stood out from each other. I could have looked at the comments code of Wordpress and messed about, but thought it would be much easier with jQuery. Here's what I did;
Step 1. Enqueue the jQuery script.
If you read my previous Wordpress and jQuery post, you'll remember that we have to "enqueue" the jquery script ready for use. Easy enough. Simply add;
wp_enqueue_script('jquery');
to the head of your template right before wp_head is called.
Step 2. Add a class to the stylesheet
We need to do this to give each alternate comment a style. Easy enough, simply add the following to your stylesheet
.alt { background: #eee; border-top: 1px solid #ccc; border-bottom: 1px solid #ccc; }
This will give a pale grey background and a darker grey top and bottom border.
Step 3. Add the jQuery code.
This is really simple. All we need to do is add this to the header of our template (which would usually be in the templates header.php file);
jQuery(document).ready(function(){ jQuery("#commentlist li:even").addClass("alt"); });
What this code does is ADD a class called "alt" (remember we just added this to the stylesheet file?) to every other comment (li) that is inside a div called commentlist. Isn't that so much easier than farting about with php code etc etc.
Enjoy!

Comment by burt — January 29, 2008 @ 9:39 pm
Oh, and if you want to see this in action have a look right here.
Comment by Toxic — January 30, 2008 @ 1:09 pm
"but thought it would be much easier with jQuery"
Doubtful, most themes comments code has "echo $oddcomment" on the li. So you just have to style .odd or .even classes in the stylesheet.
Comment by burt — January 30, 2008 @ 3:00 pm
Except if you made the theme yourself
Ahem.
Comment by Toxic — January 30, 2008 @ 5:23 pm
In which case it would be easier to add the "echo $oddcomment" in the comment form you've rustled up
Comment by burt — February 2, 2008 @ 10:24 am
You gotta move with the time, Toxie dude. Web2 is what it's all about