DataGrid Library may be used as a sort-only JavaScript plugin. It may sort any HTML content, including DIVs, lists, or tables. Let's see how to sort a basic table with random data.
Now, let's add a table with some sample data. It will contain three columns - user first name, user last name, and age. Each column has an appropriate CSS class: .age,.first-name and .last-name.
Also, let's add some styles:
Now we need to add a DataGrid CSS to the HEAD of the document:
And additionally, we need to add the DataGrid script at the bottom of the document.
All we need to do now is to define what exactly should be sorted. Let's add the data-grid attribute to the <tbody> element of the table, and data-grid-item property to each <tr> element. Now the table will look like follows:
Now let's add a sort control HTML:
You may find the detailed documentation of the sort dropdown control here.
The final step is to initialize the DataGrid library as follows:
<select data-grid-control="sort">
<option data-path=".first-name" data-direction="asc" data-type="text" selected>Sort by first name asc</option>
<option data-path=".first-name" data-direction="desc" data-type="text">Sort by first name desc</option>
<option data-path=".last-name" data-direction="asc" data-type="text">Sort by last name asc</option>
<option data-path=".last-name" data-direction="desc" data-type="text">Sort by last name desc</option>
<option data-path=".age" data-direction="asc" data-type="number">Sort by age asc</option>
<option data-path=".age" data-direction="desc" data-type="number">Sort by age desc</option>
</select>