Ok, so I was able to do price sorting, using JQuery and data-attributes. The problem is I’m unable to sort by highest, and I’m unable to get re-sort by ‘created’ again. My hunch is because $collection
only works for integers? I found this snippet online and know this is a bit beyond Django/Python so let me know if I should ask elsewhere!
/**
* This function returns a callback for data-attribute based sorting.
*
* @param sortCriteria
* Name of the data-attribute for sorting.
* @param itemsToSort
* A string selector for items for sorting.
* @param container
* A container to put items.
* @returns {Function}
*/
var sortByDataAttr = function(sortCriteria, itemsToSort, container) {
return function() {
// Grab all the items for sorting.
var $collection = $(itemsToSort);
// Sort them and append in to container.
$collection.sort(function(a, b) {
return $(a).data(sortCriteria) - $(b).data(sortCriteria)
}).appendTo($(container));
};
},
/**
* Remove class from all elements and apply to current.
*
* @param current
* HTML node to apply class.
* @param activeClass
* Active-state string class.
*/
highlightActive = function(current, activeClass) {
$('.' + activeClass).removeClass(activeClass);
$(current).addClass(activeClass);
};
// Sort by 'data-created' at the start.
highlightActive('.btn-sort-created', 'btn-sort--active');
sortByDataAttr('created', '.item', '.list');
$('.btn-sort-created').on('click', function() {
highlightActive(this, 'btn-sort--active');
sortByDataAttr('created', '.item', '.list')();
});
$('.btn-sort-price-lowest').on('click', function() {
highlightActive(this, 'btn-sort--active');
sortByDataAttr('price', '.item', '.list')();
});
$('.btn-sort-price-highest').on('click', function() {
highlightActive(this, 'btn-sort--active');
sortByDataAttr('-price', '.item', '.list')();
});