Sorting Data and CSS Cascading

In this lesson, we will look at how to use SortController

Sorting data and infinite loops

Our sortTargets method takes the list of the elements that are sortElementTargets and, well, sorts them, using the value of their data-sort-value attribute for comparison. Once it has a sorted list, it reappends them in order back to the parent, which has the effect of having all the children display in order. We also have a guard clause where nothing happens if the targets are already sorted, which also should prevent the MutationObserver from looping endlessly since the changes to the element from appending objects also qualify as mutations.

This SortController is pretty generic, and we could use it almost anywhere to keep a list of items sorted without any further JavaScript.

The timing is such that the sorting happens before the display, so our incoming element only appears to enter the DOM once in the correct location (rather than appearing at the bottom and then moving to the correct location). The animation still fires, as well, which makes the new object appear to enter from the right in the correctly sorted location.

Here’s the application we have so far:

Get hands-on with 1000+ tech skills courses.