[SalesForce] Dynamically apply style classes within a repeat tag

Is it possible to say: Every second element within apex:repeat will have a different style class?

Best Answer

This is possible, we can identify every 2nd, every 3rd element from apex:repeat and mark them with the class which we want. Please refer below code.

VFPage:

<apex:page controller="VFIndexing">
    <style>
        .redColor{
            color : red;
        }
        .blueColor{
            color : blue;
        }
    </style>
    <apex:variable var="index" value="{!1}"/>
    <apex:repeat value="{!contacts}" var="contact">
        <span class="{!IF(MOD(index,2)==0,'redColor','blueColor')}">{!contact.Name}</span><br/>
        <apex:variable var="index" value="{!index+1}"/>
    </apex:repeat>
</apex:page>

Controller Code:

public class VFIndexing {

    public List<Contact> contacts{get;set;}
    public VFIndexing(){
        contacts = [SELECT ID, Name FROM Contact LIMIT 1000];
    }
}

As a common practice mark this as a solution if this helps you.