Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations wOOdy-Soft on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Go ahead... shorten my code! 2

Status
Not open for further replies.

TheConeHead

Programmer
Aug 14, 2002
2,106
US
Here is an example of some code that I use a lot to make alternate rows of tables have differing background colors (for readability) - I know it can be shortened and am looking for options - thanks!

Code:
bgcolor=0;
while (blah == blah) {
	<tr if (bgcolor==1) { bgcolor="#cccccc" }>
							
if (bgcolor==0) {
	bgcolor=1;
} else {
	bgcolor=0;
}
blah++;
}

[conehead]
 
Just so you know, when CSS3 becomes widely supported, you will be able to use pure CSS for this:

W3C said:
Code:
tr:nth-child(2n+1) /* represents every odd row of a HTML table */
tr:nth-child(odd)  /* same */
tr:nth-child(2n)   /* represents every even row of a HTML table */
tr:nth-child(even) /* same */


Dan



[tt]Dan's Page [blue]@[/blue] Code Couch
[/tt]
 
I'm guessing that's supposed to be server side jscript with some html thrown in? You have a <tr> definition right in the middle of your script so I'm guessing there should have been some <% %> brackets in there. Anyway, to shorten it you could do this:

Code:
bgcolor=0;
while (blah == blah) {
   %><tr <%=((bgcolor++ % 2) ? 'style="background-color:#cccccc"' : '')%>><%
   blah++;
}

You know this will loop forever, right? (blah == blah) will never be false.

-kaht

[small] <P> <B> <P> <B> <P> <B> <P> <B> <P> <B> <P> <B> <P> <B> <P> <B> <P> <B> <P> <B> <P> <B> <P> <B> <P> <B> <P> <.</B>[/small]
[banghead] [small](He's back)[/small]
 
kaht beat me to it but my answer was very similar.
<%= (bgcolor++%2)?'bgcolor="#ffffff"':'bgcolor="#cccccc"';%>

It depends a lot on how your code is working and if it is indeed server side, how you are setting the bgcolor, etc.

You could have a stylesheet with a class for one color and a class for the other and then use:
<%= (bgcolor++%2)?'class="light"':'class="dark"';%>


Stamp out, eliminate and abolish redundancy!
 
In times of yore, in the days before steamships, higher math functions were shunned because of their high cost of computation. A toggle using simple arithmetic:
Code:
function toggle( i ){
  return ( 1 - i );
}

works fine as long as the parameter has been initialized as 1 or 0.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top