SyntaxStudy
Sign Up
jQuery Tracking Sort Order with .data()
jQuery Intermediate 4 min read

Tracking Sort Order with .data()

Sort Order Tracking

Store sort direction per column using .data() to toggle between ascending and descending on repeated clicks.

Example
$("th[data-col]").on("click", function() {
  const col = $(this).data("col");
  const dir = $(this).data("dir") === "asc" ? "desc" : "asc";

  // Reset all columns
  $("th[data-col]").removeData("dir").find(".sort-icon").text("⇅");

  // Set this column
  $(this).data("dir", dir)
         .find(".sort-icon").text(dir === "asc" ? "↑" : "↓");

  sortTable(col, dir);
});
Pro Tip

Reset other column sort indicators when a new column is clicked.