Skip to content

Instantly share code, notes, and snippets.

@westonganger
Last active January 10, 2025 03:27
Show Gist options
  • Save westonganger/7269df5f10f031e29dbee19755b49cf4 to your computer and use it in GitHub Desktop.
Save westonganger/7269df5f10f031e29dbee19755b49cf4 to your computer and use it in GitHub Desktop.
simple_sortable_table.js
document.addEventListener("DOMContentLoaded", function(){
var current_sort_by = null;
var sort_ascending = true;
var sort_table = function(table_el){
var tbody_el = table_el.querySelector("tbody");
var sort_col_index = table_el.querySelectorAll("th").findIndex(function(el){ return el.textContent === current_sort_by });
var sorted_row_elements = tbody_el.querySelectorAll("tr").sort(function(prev_tr_el, next_tr_el){
var prev_text = prev_tr_el.querySelectorAll("td")[sort_col_index].textContent;
var next_text = prev_tr_el.querySelectorAll("td")[sort_col_index].textContent;
if(prev_text === next_text){
return 0;
}else if(!prev_text){
// move blanks to end
return 1;
}else if(!next_text){
// move blanks to end
return -1;
}else{
var compare_val = prev_text.localeCompare(next_text, "en", {numeric: true, sensitivity: "base"});
if(sort_ascending){
return compare_val;
}else{
return -compare_val;
}
} else {
return (prev_text < next_text) ? 1 : -1;
}
});
var fragment = document.createDocumentFragment();
sorted_row_elements.forEach(function(el){
fragment.appendChild(el);
});
tbody_el.innerHTML = "";
tbody_el.append(fragment);
};
document.querySelectorAll("table.simple-sortable").forEach(function(table_el){
table_el.querySelectorAll("th.sortable").forEach(function(th_el){
th_el.style.cursor = "pointer";
th_el.addEventListener("click", function(){
var col_name = th_el.textContent;
if(current_sort_by == col_name){
sort_ascending = !sort_ascending;
}else{
current_sort_by = col_name;
sort_ascending = true;
}
sort_table(table_el);
});
});
});
var style_el = document.createElement("style");
style_el.innerHTML = `
table.simple-sortable th.sortable{
cursor: pointer;
}
table.simple-sortable th.sortable:after{
content: "↕";
padding-left: 5px;
color: #777;
}
`;
document.head.appendChild(style_el);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment