Filtering a collection by tag using a drop-down

From Shopify Wiki

Revision as of 02:19, 23 May 2012 by Chill35 (Talk | contribs)
Jump to: navigation, search

Image:Jitensha Playground — Shopify.png

To add to your collection page a drop-down that lists all tags within your collection, you can use either code snippet no 1 or code snippet no 2 below, whichever you find more elegant.

Both code snippets will work on regular collection pages — those collections you created under the Collection tab — as well as on automatic collection pages.

Code Snippet no 1

{% if collection.all_tags.size > 0 %}

<div id="collection-tags-wrapper">
  <p>Browse by tag:</p>
  <select id="collection-tags">
    <option value="" id="">All</option>
    {% for tag in collection.all_tags %}
    <option value="{{ tag | handle }}" id="{{ tag | handle }}"{% if current_tags contains tag %} selected{% endif %}>{{ tag }}</option>		
    {% endfor %}
  </select>
</div><!-- #collection-tags-wrapper -->

<script>
jQuery('#collection-tags').change(function() {
  var newUrl = '';
  var tag = jQuery(this).val();
  {% if collection.handle %}
  if (jQuery(this).val() === '') {
    newUrl = '/collections/{{ collection.handle }}';
  }
  else {
    newUrl = '/collections/{{ collection.handle }}/' + tag;
  }
  {% elsif collection.products.first.type == collection.title %}
  if (jQuery(this).val() === '') {
    newUrl = '{{ collection.title | url_for_type }}';
  }
  else {
    newUrl = '{{ collection.title | url_for_type }}&constraint=' + tag;        
  }
  {% elsif collection.products.first.vendor == collection.title %}
  if (jQuery(this).val() === '') {
    newUrl = '{{ collection.title | url_for_vendor }}';
  }
  else {
    newUrl = '{{ collection.title | url_for_vendor }}&constraint=' + tag;        
  }
  {% endif %}
  window.location.href = newUrl;
});
</script>

{% endif %}

Code Snippet no 2

{% if collection.all_tags.size > 0 %}
<div id="collection-tags-wrapper">
  <p>Browse by tag:</p>
  <select id="collection-tags">
    <option value="" id="">All</option>
    {% for tag in collection.all_tags %}
    <option value="{{ tag | handle }}" id="{{ tag | handle }}"{% if current_tags contains tag %} selected{% endif %}>{{ tag }}</option>		
    {% endfor %}
  </select>
</div><!-- #collection-tags-wrapper -->

<script>
jQuery('#collection-tags').change(function() {
  var tag = jQuery(this).val();
  if (tag === '') {
    {% if collection.handle %}
    window.location.href = '/collections/{{ collection.handle }}';
    {% elsif collection.products.first.type == collection.title %}
    window.location.href = '{{ collection.title | url_for_type }}';
    {% elsif collection.products.first.vendor == collection.title %}
    window.location.href = '{{ collection.title | url_for_vendor }}';
    {% endif %}
  } 
  else {
    window.location.href = jQuery('{{ 'tag' | link_to_tag: 'tag' }}').attr('href').replace('tag', tag);
  }
});
</script>
{% endif %}

Related Articles