Add class to every 3rd element - liquid cycle or jquery?

Shopify Partner
375 0 5

I would like to add a class to every third element output.

For example, if I am listing products on a collection page every third product output would have a class of .last. I would then apply some css to that class.

Can you do this with liquid using cycle or should I handle it with jQuery?

Either way can someone point me in the direction to achieve this?

Fine Art and Photography by Matt Mikulla --> http://mattmikulla.com
0 Likes
Shopify Expert
3933 15 323

http://forums.shopify.com/categories/2/posts/36447

 

Custom Shopify Apps built just for you! hunkybill@gmail.com http://www.resistorsoftware.com
0 Likes
Shopify Partner
375 0 5

Thanks @HunkyBill. That was easy.

 

Fine Art and Photography by Matt Mikulla --> http://mattmikulla.com
0 Likes
Tourist
6 0 0

This link is not working:

http://forums.shopify.com/categories/2/posts/36447

@HunkyBill Can you please tell me the solution for it?

0 Likes
Shopify Expert
3933 15 323

Use the cycle.

Custom Shopify Apps built just for you! hunkybill@gmail.com http://www.resistorsoftware.com
1 Like
Tourist
6 0 0

Can you tell me how to use cycle in this particular scenario? Sorry but I am little confused in it

0 Likes
Tourist
11 2 2

I came across this same problem and was able to locate an archive of the page in question:

 

https://web.archive.org/web/20130424124956/http://ecommerce.shopify.com/c/ecommerce-design/t/for-loo...

 

Here's the example provided on that page:

 

<ul>
{% for product in collection.products %}
<li class="item-{% cycle '1', '2', '3', '4' %}">{{ product.title }}</li>
{% endfor %}
</ul>
0 Likes
Shopify Partner
1 0 0

Hey ahmad, I second that link not working.

For you and anyone else, this is how I achieve using the modulo filter:

 

//If you need modular access throughout loop, try this:
{% for something in many_things %}
{% assign every_third = forloop.index | modulo:3 %} // Divides an output by a number and returns the remainder. {% if every_third == 0 %} Do Something Crazy! {% endif %} // if the remainder is 0, being 3 is a prime number, it's a third item!

//If you just need a class for every third item, try this:**

<li class="{% cycle '','','third-class-here' %}"></li>

You can modify this in many ways, targeting certain numbers, simplifying etc..

See more on math filters here: https://help.shopify.com/en/themes/liquid/filters/math-filters#modulo

Hope this helps someone! 

A creator inspired by THE creator
Serving Non-profits, E-commerce & Artists alike
0 Likes
Highlighted
Shopify Expert
3933 15 323

The cycle can be used elegantly, and is perfect for doing funky things in loops. Modern documentation location is here. 

 

https://help.shopify.com/en/themes/liquid/tags/iteration-tags

 

 

 

 

Custom Shopify Apps built just for you! hunkybill@gmail.com http://www.resistorsoftware.com
0 Likes