Skip to content

Instantly share code, notes, and snippets.

@cfxd
Last active October 18, 2020 13:57
Show Gist options
  • Save cfxd/863f956a35e6d58a5e7f8760f28712cf to your computer and use it in GitHub Desktop.
Save cfxd/863f956a35e6d58a5e7f8760f28712cf to your computer and use it in GitHub Desktop.
Add a sort by dropdown in Shopify (the right way). See https://cfxdesign.com/add-a-sort-by-dropdown-in-shopify-the-right-way
// Save existing sort parameters
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]);
}
}
}
// Add existing sort parameters to current URL (ES6)
document.querySelector('.sort-by').addEventListener('change', (e) => {
const { value } = e.currentTarget;
Shopify.queryParams.sort_by = value;
location.search = new URLSearchParams(Shopify.queryParams).toString();
});
<script type="text/javascript">
// Save existing sort parameters
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]);
}
}
}
// Add existing sort parameters to current URL
document.querySelector('.sort-by').addEventListener('change', function(e) {
var value = e.currentTarget.value;
Shopify.queryParams.sort_by = value;
location.search = new URLSearchParams(Shopify.queryParams).toString();
});
</script>
// Save existing sort parameters
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]);
}
}
}
// Add existing sort parameters to current URL
document.querySelector('.sort-by').addEventListener('change', function(e) {
var value = e.currentTarget.value;
Shopify.queryParams.sort_by = value;
location.search = new URLSearchParams(Shopify.queryParams).toString();
});
<div class="sort-by--container">
<label for="sort-by">Sort by</label>
<select id="sort-by" class="sort-by">
{% for option in collection.sort_options %}
<option value="{{ option.value }}"{% if option.value == collection.sort_by %} selected{% endif %}>{{ option.name }}</option>
{% endfor %}
</select>
</div>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment