h0bb5 h0bb5 - 2 months ago 15
jQuery Question

How to use nth-child on a filtered list?

I am pulling a list of images/items from a database and filtering them based on category.

The design requirements are a tiled/mosaic layout with a large square on the 7th item, and a larger rectangle on the 8th item, on ALL filters. Meaning the larger squares cannot be in a different order.

Currently my approach is to use nth-child selectors to select the 7th and 8th from the list of items:

/* create big item block */
.grid-item:nth-child(7n) {
height: 24em;
width: 50%;
}
/* create rectangle item block */
.grid-item:nth-child(8n) { width: 50%; }


This is a problem since it only affects the overall list. How can I target the 7th and 8th item in the filtered list after the button/category is selected?

Here is a codepen with the correct layout I am trying to achieve for the view-all filter. I am trying to achieve this same layout but with different items based off the filter. If you select 'thank-you' category, you can see the big square is pulled into the 3rd place on this list and still remains a large square due to the nth-child selector.

http://codepen.io/H0BB5/pen/BLNLWy

Answer

You want to select the "nth visible item" - which is a case for :nth-of-type (the "type" being "visible items"), not :nth-child.

After the filtering has been done, run a function something like

  $('.grid-item').each(function(){        // for every .grid-item
    if ($(this).css("display") != "none") // if it isn't display:none
      $(this).addClass("matched")         // give it .matched
  });

to mark the visible items. Then you can target your ones of interest with nth-of-type (the following modified from the code in your question):

/* create big item block */
.matched:nth-of-type(7n) { 
  height: 24em;
  width: 50%; 
}
/* create rectangle item block */
.matched:nth-of-type(8n) { width: 50%; }

Keep in mind that for your example the :nth-of-type(56n) (7*8) will match the last style given, so the :nth-of-type(8n) style. If you want every 56th item to get the styles of every seventh, write your .matched:nth-of-type(7n) after your .matched:nth-of-type(8n) styles.

Comments