Keith Power
Keith Power

Reputation: 14141

set every 1st and fourth element with a class

I have a jquery carousel set to 620px wide. I am using the grid 960 to place the images inside. I show 4 images at a time.

In order to do that I set the every first image class to 'grid_2 alpha' and every fourth to 'grid_2 omega' in the group of 4 shown while all in between I set to just grid_2.

This gives me the 620px I need. I am pulling from the database and I am trying to set the class dynamically but cant quite get every first and fourth in the group with the classes.

                    <?php $loopIndex = 1; ?>
                    <?php foreach ($pub_values as $v) { 
                    if($v['pub_of_the_month'] == 1)
                    {
                    ?>
                    <?php if ($loopIndex == 1 || $grid_class=="grid_2 omega") $grid_class="grid_2 alpha";
                            else if($loopIndex%4 == 0) $grid_class="grid_2 omega"; 
                            else $grid_class="grid_2"; 
                          $filename = "images/pub_images/120x160/".$v['id'].".jpg";
                          if (!file_exists($filename)) $filename = "images/pub_images/120x160/blank.gif";       
                    ?>
                        <div class="<?php echo $grid_class?>">
                            <a href="#">
                                <img src="<?=$filename;?>" alt="<?=$v['name'];?>" width="120" height="160" />
                                <?=$v['name'];?>
                            </a>
                        </div>
                    <?php $loopIndex = $loopIndex + 1; } }?>

The above code is my best attempt of achieving the following.

Images

1 - grid_2 alpha

2 - grid_2

3 - grid_2

4 - grid_2 omega

5 - grid_2 alpha

6 - grid_2

7 - grid_2

8 - grid_2 omega

9 - grid_2 alpha

Upvotes: 2

Views: 2376

Answers (2)

Mārtiņš Briedis
Mārtiņš Briedis

Reputation: 17752

Simple math, dividing with a remainder.

Maybe you can figure out by looking a this code:

for($i = 1; $i <= 9; $i++){
    echo "\n $i ";
    if($i % 4 == 1){
        echo " alpha";
    }elseif($i % 4 == 0){
        echo " omega";
    }
}

Live example: http://codepad.org/LIepxlJm

Upvotes: 3

mindandmedia
mindandmedia

Reputation: 6825

maybe you should just use a for-loop:

for ($i = 0; $i< sizeof($pub_values); $i++) { 
   $classes =['grid_2'];
   if($i%4 == 0) $classes[] = 'alpha';
   if($i%4 == 3) $classes[] = 'omega';
}

edit: this is just trying to show an approach, not trying to be syntactically correct. in the end, you want to join (or implode in php) your classes to get the string.... (not implemented for you either)

Upvotes: 1

Related Questions