Jump to content


Photo

function to alternate row colours not working


  • Please log in to reply
2 replies to this topic

#1 shocker-z

shocker-z
  • Members
  • PipPipPip
  • Advanced Member
  • 864 posts
  • LocationNottingham

Posted 08 May 2006 - 01:23 PM

My code below is outputting 'bg2' all the time and not alternating..
can anyone see what i've done wrong?
bg1, bg2 are both classes stores in an attached CSS sheet
<?php
$row_count=1;

function altcolor($link) {
$bg1='bg1';
$bg2='bg2';
$class = ($row_count % 2) ? $bg1 : $bg2;
echo("class='$class' onmouseover=\"this.className='bgmouseover'\" onmouseout=\"this.className='$class'\" onclick=\"location.href='index.php?cat=profiles&page=viewprofile&username=$link'\"");
$row_count++;
}
?>


Regards
Liam
www: www.ukchat.ws | irc: irc.ukchat.ws chan: #blufudge

#2 kenrbnsn

kenrbnsn
  • Staff Alumni
  • Advanced Member
  • 8,235 posts
  • LocationHillsborough, NJ, USA

Posted 08 May 2006 - 01:33 PM

It's not alternating because the variable $row_count is not known to the function so it's value is zero every time you enter the function.

In the function either add a "global" statement:
<?php
$row_count=1;

function altcolor($link) {
   global $row_count;  // added
   $class = ($row_count % 2) ? 'bg1' : 'bg2';
   echo("class='$class' onmouseover=\"this.className='bgmouseover'\" onmouseout=\"this.className='$class'\" onclick=\"location.href='index.php?cat=profiles&page=viewprofile&username=$link'\"");
   $row_count++;
}
?>
Or make the function accept the value of $row_count as a parameter and return the next value of row_count:
<?php
$row_count=1;
//
//
$row_count = altcolor($link,$row_count);   //<-- sample call of the function
//
function altcolor($link,$rc) {
$class = ($rc % 2) ? 'bg1' : 'bg2';
echo("class='$class' onmouseover=\"this.className='bgmouseover'\" onmouseout=\"this.className='$class'\" onclick=\"location.href='index.php?cat=profiles&page=viewprofile&username=$link'\"");
return($rc++);
}
?>

Many people seem prefer the second method over the first.

Ken

#3 shocker-z

shocker-z
  • Members
  • PipPipPip
  • Advanced Member
  • 864 posts
  • LocationNottingham

Posted 08 May 2006 - 02:08 PM

thanks alot! thats great mate :) i never realised that it didnt take in variables from the outside or aless stated as global.. maby that has caused me un nessorcery headaches in the past :) i prefer the first option :)

Thanks alot
Liam
www: www.ukchat.ws | irc: irc.ukchat.ws chan: #blufudge




0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users