carolineschnapp
5/7/2014 - 3:11 PM

JavaScript tag to place at the bottom of collection.liquid to handle both the .sort-by select and the .coll-filter selects.

JavaScript tag to place at the bottom of collection.liquid to handle both the .sort-by select and the .coll-filter selects.

<script>
  Shopify.queryParams = {};
  if (location.search.length) {
    for (var aKeyValue, i = 0, aCouples = location.search.substr(1).split('&'); i < aCouples.length; i++) {
      aKeyValue = aCouples[i].split('=');
      if (aKeyValue.length > 1) {
        Shopify.queryParams[decodeURIComponent(aKeyValue[0])] = decodeURIComponent(aKeyValue[1]);
      }
    }
  }
  var collFilters = jQuery('.coll-filter');
  collFilters.change(function() {
      var newTags = [];
      var newURL = '';
      collFilters.each(function() { 
        if (jQuery(this).val()) {
          newTags.push(jQuery(this).val());
        }
      });
      {% if collection.handle %}
      newURL = '/collections/' + '{{ collection.handle }}';
      if (newTags.length) {
        newURL += '/' + newTags.join('+');
      }
      var search = jQuery.param(Shopify.queryParams);
      if (search.length) {
        newURL += '?' + search;
      }
      location.href = newURL;    
      {% else %}
      if (newTags.length) {
        Shopify.queryParams.constraint = newTags.join('+');        
      }
      else {
        delete Shopify.queryParams.constraint;
      }
      location.search = jQuery.param(Shopify.queryParams);
      {% endif %}      
  });
  jQuery('.sort-by')
    .val('{{ collection.sort_by }}')
    .bind('change', function() {
      if (jQuery(this).val()) {
        Shopify.queryParams.sort_by = jQuery(this).val();                
      }
      else {
        delete Shopify.queryParams.sort_by;
      }
      var search = jQuery.param(Shopify.queryParams);
      if (search.length) {
        location.search = jQuery.param(Shopify.queryParams);
      }
      else {
        location.href = location.pathname;
      }
    });
</script>