Last active
May 15, 2018 21:18
-
-
Save zomars/78cf2ef3479eb737a7935ac7918a8301 to your computer and use it in GitHub Desktop.
Sort products in Shopify via dropdown in vanilla JavaScript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{%- comment -%} | |
Put it in your snippets folder and include it in your templates: | |
{% include 'sort-by' %} | |
{%- endcomment -%} | |
<div id="sort-by-container"></div> | |
<script> | |
// Get the URL search parameters | |
const params = new URLSearchParams(location.search); | |
const currentParams = params.get('sort_by'); | |
const render = function (template, node) { | |
node.innerHTML = template; | |
node.querySelector('#sort-by').addEventListener('change', function() { | |
// Change the parameters on dropdown value change | |
params.set(this.name, this.value); | |
// Redirect to URL with new parameters | |
window.location = `${location.pathname}?${params}`; | |
}); | |
}; | |
const SortOptions = [{ | |
label: 'Featured', | |
value: 'manual' | |
}, { | |
label: 'Price: Low to High', | |
value: 'price-ascending' | |
}, { | |
label: 'Price: High to Low', | |
value: 'price-descending' | |
}, { | |
label: 'A-Z', | |
value: 'title-ascending' | |
}, { | |
label: 'Z-A', | |
value: 'title-descending' | |
}, { | |
label: 'Oldest to Newest', | |
value: 'created-ascending' | |
}, { | |
label: 'Newest to Oldest', | |
value: 'created-descending' | |
}, { | |
label: 'Best Selling', | |
value: 'best-selling' | |
}]; | |
const template = ` | |
<div> | |
<label for="sort-by">Sort by</label> | |
<select id="sort-by"> | |
${SortOptions.map((item) => | |
`<option value="${item.value}" ${currentParams === item.value ? 'selected' : ''}>${item.label}</option>` | |
).join('')} | |
</select> | |
</div> | |
`; | |
render(template, document.querySelector('#sort-by-container')); | |
</script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment