Ad

Shopify Collection Sort Method Not Working

- 1 answer

Shopify recommends using this code for making a "Sort By" drop down on their collection pages: https://gist.github.com/carolineschnapp/11352987

I am building a new theme with Shopify Slate and this code doesn't work for me. Fortunately, another developer has commented on this and supplied a better code. Here is the code:

document.querySelector('#sort-by').addEventListener('change', function() {
  const urlSearchParams = new URLSearchParams(window.location.search);
  urlSearchParams.set(this.name, this.value);
  window.location = `?${urlSearchParams}`;
});

Unfortunately this didn't work off the get go due to it not adding "sort_by" to the search parameter. I adapted the second-last line of this code to look like this:

window.location = `?sort_by${urlSearchParams}`;

This worked, but whenever I tried to change the parameter, the page kept reloading and adding multiple "sort_by"'s to the URL (ex. ?sort_bysort_by=price-descending&=title-ascending)

Is there any way I can change this code so that "sort_by" only appears once in the URL?

Ad

Answer

What happens if you swap window.location.search with:

window.location.search.indexOf("sort_by") > -1 
? window.location.search.replace(/sort_by/gi,"")
: window.location.search

so it becomes:

new URLSearchParams(
 window.location.search.indexOf("sort_by") > -1 
    ? window.location.search.replace(/sort_by/gi,"")
    : window.location.search
)
Ad
source: stackoverflow.com
Ad