Skip to content

Instantly share code, notes, and snippets.

@zomars
Last active May 15, 2018
Embed
What would you like to do?
Sort products in Shopify via dropdown in vanilla JavaScript
{%- 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