Alternating background colors: JS v PHP

Out of pure curiosity:

Assuming tabulated data in HTML is being generated by a PHP script, would it be better to alternate each row’s background color with PHP or rely on JS to do it?

One is run client-side and the other server-side so my guess you have to take the whole web app as a whole and see which side should be spared the additional workload. Is it situational or is there an absolute rule?

In a vacuum, I guess you could argue PHP would be better since it cannot be turned off in the way JS can (unless plugins like NoScript can block PHP as well), but I don’t have enough experience with either to be sure.

Thanks :slight_smile:

You only need a odd or even class, but not both. Both is not really necessary considering the default can be the even than you create a more specific selector for the odd, targeting the odd class. Nothing really to split hairs over, just something to consider for the next project. Also, using something like even or odd is a little nicer than evenRow or oddRow. Both oddRow and evenRow only restate the obvious holding no actual purpose. I always use odd, myself.

For this type of scenario - yes.

You can do it with JS but then if it’s critical to have alternate row colours then you will need a Plan B for those, albeit very small number, who have JS turned off for whatever reason.

Understood. Ha, I de-railed my own thread :lol:

So you would advocate using PHP in all circumstances and leaving JS alone?

in my loop that generates each row I would have something similar to this

 
$rowClass = ($rowClass == 'oddRow')? 'evenRow' : 'oddRow';    //this toggles the class name for each row
 
echo '<tr class="'.$rowClass.'">';

and then set the styles for each class name.

I need both where both the oddRow and evenRow styles are different to the default style.

Whether you use oddRow/evenRow or just odd/even is a personal choice. I prefer to use the more descriptive class name so I can easily distinguish it from say odd and even list items, for example, in the stylesheet.

Do you actually use two class names for each or have a default row color and use a single additional class to define the alternating color?

I’m probably splitting hairs, but if you have a large table of data then wouldn’t the extra bytes from typing class=‘evenRow’ make it a bit bloated?

with tabulated html data generated by php I use css to alternate each rows background color by using php to give each row alternate class names and then setting the css to whatever.

eg - alternate the class for each row between something like class=‘oddRow’ and class=‘evenRow’