Skip to content

Instantly share code, notes, and snippets.

@dgrammatiko
Last active December 11, 2020 12:20
Show Gist options
  • Save dgrammatiko/bb563c1b8d22f4df4818a7496603a895 to your computer and use it in GitHub Desktop.
Save dgrammatiko/bb563c1b8d22f4df4818a7496603a895 to your computer and use it in GitHub Desktop.
/**
* How can we get the container?
* Any valid querySelector option...
*/
const gridSelector = '.grid';
/**
* How can we get the container items?
* Any valid querySelectorAll option...
*/
const gridItemSelector = '.grid-item';
/**
* How can we get the cotroling buttons?
* Any valid querySelectorAll option...
*/
const buttonSelector = 'button[data-sort]';
/**
*
* @param {*} param0
*/
const sortElements = ({ container, childSelector, getScore, sortBy, direction }) => {
const items = [...container.querySelectorAll(childSelector)];
items.sort((a, b) => {
b = getScore(b);
a = getScore(a);
if (direction === 'desc') {
if (sortBy === 'name') {
return b.localeCompare(a, 'en', { sensitivity: 'base' });
} else if (sortBy = 'date') {
return Math.round((new Date(b)).getTime() / 1000) - Math.round((new Date(a)).getTime() / 1000);
} else {
return b - a;
}
} else {
if (sortBy === 'name') {
return a.localeCompare(b, 'en', { sensitivity: 'base' });
} else if (sortBy = 'date') {
return Math.round((new Date(a)).getTime() / 1000) - Math.round((new Date(b)).getTime() / 1000);
} else {
return a - b;
}
}
}).forEach(item => {
container.appendChild(item)
});
};
[].slice.call(document.querySelectorAll(buttonSelector)).forEach(button => {
button.addEventListener('click', (event) => {
const el = event.target;
const data = el.dataset;
sortElements({
container: document.querySelector(gridSelector),
childSelector: gridItemSelector,
getScore: item => {
return item.dataset[data.sort];
},
sortBy: data.sort,
direction: data.sortDirection,
});
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment