Sortable List Template

An interactive list where users can re-sort the content based on different criteria.

This component is perfect for directories, product listings, or any data list where providing sorting options enhances the user experience.

A screenshot of a list with 'Sort by Name' and 'Sort by Popularity' buttons above it.

Get Source Code Preview

About this Template

This template uses vanilla JavaScript to add sorting functionality to a list. Users can click buttons to instantly reorder the list items. The component is designed to sort by either the item's text content or a custom data attribute, making it highly flexible. This example uses a visible "Popularity Score" that is read from an HTML data-* attribute, providing clear user feedback for the sort action.

Features

Code Breakdown

The JavaScript first selects the sorting buttons and the ul element containing the list items. It adds a click event listener to each button.

When a button is clicked, its handler first converts the NodeList of list items into a proper JavaScript Array, which is necessary to use the sort() method. It then calls the sort() method on this array. Inside the sort's comparison function, it checks which button was clicked. If the "Sort by Name" button was clicked, it compares the textContent of the items. If "Sort by Popularity" was clicked, it retrieves and compares the value of the data-popularity attribute.

After the array is sorted, the script loops through the sorted array and uses the appendChild() method to re-add each list item to the parent ul. Since an element can only exist in one place in the DOM, appendChild() automatically moves the item to the end of the list, effectively reordering the entire list based on the sorted array.

Code

Here's the full code for the template:

View Output