$(document).ready(function() { // Sorting state management const sortState = {}; // Function to sort articles function sortArticles(columnClass) { const $list = $('.alist'); const $listItems = $list.children('li'); // Determine sort direction if (!sortState[columnClass]) { sortState[columnClass] = 'asc'; } else { sortState[columnClass] = (sortState[columnClass] === 'asc') ? 'desc' : 'asc'; } // Sort the list items based on the text of the specified column $listItems.sort(function(a, b) { const aText = $(a).find('.' + columnClass).text().trim().toLowerCase(); const bText = $(b).find('.' + columnClass).text().trim().toLowerCase(); // Special handling for period (numeric sorting) if (columnClass === 'period') { const aNum = parseInt(aText); const bNum = parseInt(bText); return sortState[columnClass] === 'asc' ? aNum - bNum : bNum - aNum; } // Default alphabetical sorting return sortState[columnClass] === 'asc' ? aText.localeCompare(bText) : bText.localeCompare(aText); }); // Detach and reappend sorted items to maintain DOM structure $list.empty().append($listItems); // Update sort direction indicators $('.legend li').removeClass('sort-asc sort-desc'); $(`.legend li[data-sort="${columnClass}"]`).addClass( sortState[columnClass] === 'asc' ? 'sort-asc' : 'sort-desc' ); } // Add click event to legend spans for sorting $('.legend li').on('click', function() { const columnClass = $(this).attr("data-sort"); // If the column exists in the article items, sort by that column if ($('.alist li').first().find('.' + columnClass).length > 0) { sortArticles(columnClass); } }); // Toggle content visibility $(".alist").on('click', 'li', function(e) { // Prevent sorting when clicking on content if (!$(e.target).closest('.legend').length) { // Check if click is outside content-wrapper and not on its child elements if (!$(e.target).closest('.content-wrapper').length) { const $contentWrapper = $(this).find('.content-wrapper'); $contentWrapper.toggleClass("open"); } } }); });