Shopify Collection Sort Method Not Working

- 1 answer

Shopify recommends using this code for making a "Sort By" drop down on their collection pages:

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(;
  urlSearchParams.set(, 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?



What happens if you swap with:"sort_by") > -1 

so it becomes:

new URLSearchParams("sort_by") > -1