Last active
October 18, 2020 13:57
-
-
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
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
// 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(); | |
}); |
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
// 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(); | |
}); |
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
<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