Click to See Complete Forum and Search --> : Alternating colors


rugrat15834
07-01-2006, 10:07 PM
Me again-I usually have fairly simple questions though so I suppose I pose no real threat per say. My question of the week is, how does one go about making colors to alternate, like you might see in guest book entries?. Also-I have written a short script for testing regular expressions-to see what the results would be if run that is. If anyone is interested I would be more than glad to post the code, maybe I might be able to finally contribute to something (perl & perl people) which has been so good to me. Dave :)

robertketter
07-02-2006, 06:37 AM
Dave,

I use a counter to alternate colors.

$count = 0;
foreach $line (@all){
$count++;
#blah blah blah
if ($count eq 2){ $line_color = "blue"; $count = 0; } # changes line color based on count
}# end foreach


This is really generic... but I am hoping it makes sense.

Robert Ketter - www.RobertKetter.com :)

CyCo
07-02-2006, 10:37 AM
You could use something like this in a variety of ways.
#!/usr/bin/perl

use strict;
use CGI ':standard';

my $rows = '';
my $color = '';

for (1..22) {
$color = ($color eq '#eee') ? '#ddd' : '#eee';
$rows .= div({-style=>"background-color:$color"}, $_);
}

print header, start_html('Alternating Row Colors'), $rows, end_html;

Nedals
07-03-2006, 06:23 PM
Here's a similar method to CyCo's.

#!/usr/bin/perl
use strict;
use CGI ':standard';

my $rows = '';
my $toggle = 1;

for (1..22) {
$toggle ^= 1; ## changes state for each iteration
my $color = ($toggle) ? '#ddd' : '#eee';
$rows .= div({-style=>"background-color:$color"}, $_);
}

print header, start_html('Alternating Row Colors'), $rows, end_html;

CyCo
07-03-2006, 07:23 PM
Nice touch, Nedals!

Waylander
07-03-2006, 08:25 PM
Use modulus, I dont know this language but the operator should work.
Looking for an uneven remainder in a count integer is a clean way to do it, with less variables.


$count = 0;
foreach $line (@all)
{
$color = ((($count++)%2)<1) ? '#ddd' : '#eee';
# do something with color and line
}

LeeU
07-05-2006, 10:08 AM
You can find a JavaScript solution here (http://javascript.internet.com/css/automatic-coloured-rows.html).

subesc
07-13-2006, 09:21 AM
I also normally use Waylander's method with the modulus operator.
This way, you can still have an accurate number of the amount of rows used (if needed) and you don't have to worry about resetting the $count variable.

toicontien
07-13-2006, 02:31 PM
Working on subesc's suggestion, you can alter Waylander's code just little:

$count = 0;
foreach $line (@all)
{
$html_class_name = ($count%2==0) ? 'rowA' : 'rowB';
# do something with the HTML classname
}

In my case, I use it to alternate the class name of an HTML tag so you can control the colors with an external stylesheet. It's less clutter in your HTML file and the class names are meaningful too. You know one is row a and the other is row b :) Do with it as you will.