Iterate certain classes over elements in Jquery

In my page I have pairs of divs like this:

 <div class="rounded red">

	<p>Integer egestas neque vitae dui ultricies vel venenatis mi varius! </p>

 </div>

 <div class="client rounded">

	<p>Client Name<br />
Client Company Name</p>

 </div>

 <div class="rounded red">

	<p>Integer egestas neque vitae dui ultricies vel venenatis mi varius! </p>

 </div>

 <div class="client rounded">

	<p>Client Name<br />
Client Company Name</p>

 </div>

Where I need to assign the second div in the pair with the class “client rounded” a third class that will stagger each occurrence of “client rounded” a certain amount before returning to the start position.

I have four CSS classes set up to accomplish this, (client 1-4) and so I’m trying to figure out a way to tell JQuery to count every four divs, assign the appropriate classes, then re-start the count with the next div. I know basically no Jquery, so I’ve been trying to cobble together a solution with little success. I also tried the Jquery Iterate plugin, which based on the description would have done exactly what I needed if I could’ve gotten it working.

Here’s what I have right now:


$('article div.client').addClass(function() {
  return 'client' + $(this).index();
});

This works, kinda, in that it at least added the new class whereas the other solutions didn’t. Unfortunately it counts EVERY div, not just the ones with the class .client, I can’t set my array of desired classes, and I have no idea how to make it restart the count after it hits #4. Any help would be much appreciated.

I think you could achieve this using nth-child stuff. Like this:

$('article div.client.rounded:nth-child(4n)').addClass('stagger');

I know you want to add a number after the class. What’s that for? Since I’m not sure what the number is supposed to be (which index exactly?) I’m not sure what to add yet.

The number is arbitrary; I just added it to differentiate the various degrees of stagger. Here’s what they look like in the CSS.


client1{/*left*/
	float:left;
}

.client2{/*mid-left*/
	float:left;
	margin-left:20%;
}

.client3{/*almost there*/
	float:left;
	margin-left:40%;
}

.client4{/*far right*/
	float:right;
}

And wouldn’t using nth-child add the class to every fourth div, not to each div in a “set” of four?

I get it now. How about this:

$('article div.client.rounded').each(function(i) {
  $(this).addClass('client' + ((i % 4) + 1));
});

Perfect!

I’m actually trying learn JQuery so that I don’t end up scratching my head for hours when problems like these come up. If I understand the code you’ve given me, it basically says:

For each ‘article div.client.rounded’, execute this iteration function:
Add the class ‘client’ + (# in the iteration out of 4(?) + 1) to the current div being examined.

So does the count start at 0, then, in order for the “x out of 4” logic to work? Or did I misread that part of the statement?