So I'm trying to sort some elements by a couple of data-attributes.
One is Price which will have a number from 1-4. I've figured out how to do it by lowest but can't seem to get Sort by highest to work.
Second is by Created by, which is outputting a date/time from my django backend.
My question:
- How do I get to sort by HIGHEST price working? Lowest works currently
- How do I get Sort by CREATED BY working? It currently isn't working at all.
Sample element:
<li class="browse-item" data-price="1" data-created="Oct. 10, 2018, 3:25 a.m.">
<a href="#</a>
<p>Oct. 10, 2018, 3:25 a.m.</p>
<p>1</p>
</li>
Here's what my Javascript currently looks like - I found it online and very new to programming in general.
/**
* 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', '.browse-item', '.browse-list');
$('.btn-sort-created').on('click', function() {
highlightActive(this, 'btn-sort--active');
sortByDataAttr('created', '.browse-item', '.browse-list')();
});
$('.btn-sort-price-lowest').on('click', function() {
highlightActive(this, 'btn-sort--active');
sortByDataAttr('price', '.browse-item', '.browse-list')();
});
$('.btn-sort-price-highest').on('click', function() {
highlightActive(this, 'btn-sort--active');
sortByDataAttr('-price', '.browse-item', '.browse-list')();
});