Skip to Main Content

Do-It-Yourself LibGuide Enhancements: Sortable Tables

A companion to a presentation given at the 2019 Hawaii Library Association Annual Conference by librarian Ralph Toyama, on how libraries can add features to their LibGuides environment using custom CSS and JavaScript.

Example of a Sortable Table

Lists like this were on an earlier version of our Course Reserves page.

Click on one of the first three table column names (shown in yellow) to sort the table.

Course Instructor Title Format Type and Copies Location
ECON 130 Apuya, M. Modern Principles: Microeconomics (4th ed) PC 100 (2 copies) See Circulation Desk
ECON 131 Apuya, M. Modern Principles: Macroeconomics(4th ed) PC 101 (2 copies) See Circulation Desk
HWST 276 Archer, L. Finding Meaning: Kaona and Contemporary Hawaiian Literature

PS283 .H3 M33 2016

Online. 1 user only.

 

See Circulation Desk

Online access Collections>Course Reserves Titles)

HWST 107 Blair-Stahn, C. Hawai'i: Center of the Pacific (2nd ed) PC 112 See Circulation Desk
PACS 108 Blair-Stahn, C. We Are the Ocean: Selected Works

PR9655.9 .H38 A6 2008

Online. Unlimited users.

See Circulation Desk

Online access

SOC 100 Brekke, E. Introduction to Sociology (2nd ed) PC 145 See Circulation Desk
SOC 251 Brekke, E. Marriages & Families: Changes, Choices, and Constraints PC 118 See Circulation Desk
ANTH 152 Cai, W. Pearson Custom Anthropology for Anth 152 PC 121 See Circulation Desk
MUS 121C Choi, J. Alfred's Piano 101, Book 1:  An Exciting Group Course for Adults Who Want to Play Piano for Fun Online. 2 concurrent users only.  Online access
IS 107V Chou, L. The Student Leadership Challenge: Five Practices for Becoming and Exemplary Leader, 2nd ed. Online. Unlimited users.  Online access
BOT 130 Elliot, D. Hawaiian Plant Life:  Vegetation and Flora Online. Unlimited users.  Online access
HSER 100 Williams, G. I Never Knew I Had a CHOICE: Explorations in Personal Growth PC 115 See Circulation Desk
ENG 100 Williams, T. English Composition: Connect, Collaborate, Communicate Online. (OER - Unlimited users) Online access
PHIL 110 Williamson, G. Logic Print. 3 copies. See Circulation Desk
HIST 231 Wong, N. The West in the World (3rd ed.) Print. See Circulation Desk
HIST 231 Wong, N. The West in the World: Renaissance to Present (3rd ed.) Print. 3 copies. See Circulation Desk
SP 151 Yokotake, C. Communication: Embracing Difference (4th ed.) PC 103 See Circulation Desk
ANTH 152 Young, F. At Home and in the Field Online. Unlimited users. Online access

Creating Sortable Tables

This sortable table uses JavaScript from W3Schools.com, which is shown in the box below.

You need to add code to the HTML for the table, and you have to create and upload the script file.

Table HTML Code

For a table with labeled columns, it is good practice for the cells in the top row to be tagged as table headers (<th>) rather than table data (<td>) in the HTML code. This is for accessibility reasons, as it allows screen reading programs to read out the contents of a table in a way that gives context to the data.

In the HTML code for your table, for the columns you want to be able to sort on, include in the table header <th> tags these attributes: onclick="sortTable(0)" and onkeypress="sortTable(0)"

Use the number 0 for the table's first column, 1 for the second column, etc.

Also, add the attribute tabindex="0" to each header tag. Always use the number zero.

The tabindex attribute is for accessibility purposes; it allows the column headers to be selected using the Tab key on the keyboard. This allows someone who is unable to use a mouse to activate the sorting function using a keyboard or adaptive device.

The code for the first header tag, with the added attributes, will look like this:

<th class="ck_border"  onclick="sortTable(0)"  onkeypress="sortTable(0)"  tabindex="0"  style="border: 1px solid rgb(221,221,221); border-image: none; background-color: rgb(64,64,64);" >Course</th>

The code for the second header tag, with the added attributes, will look like this:

<th class="ck_border"  onclick="sortTable(1)"  onkeypress="sortTable(1)"  tabindex="0"  style="border: 1px solid rgb(221,221,221); border-image: none; background-color: rgb(64,64,64);" >Instructor</th>

Create and Upload the Script File

Create a script file by copying the code in the Table Sorting Code box below into a text editor like Windows Notepad. Save the file with a name that ends with ".js", I named my file "tablesorter.js."

Upload the file to LibGuides using their Upload Customization Files function in Admin > Look & Feel > Custom JS/CSS. Make note of the "Include Code" shown for that file.

At the bottom of the HTML box for your table, add the "include code" to make the script act on your table.

The line would look like this:

<script type="text/javascript" src="//libapps.s3.amazonaws.com/sites/5173/include/tablesorter.js"></script>
In some cases, the script link has to be placed below the code creating the object that the script has to act on. In this case, sorting will work whether or not the link is below the table code.

Focus Indicator

For the example table above, I added a line to the stylesheet to put a prominent blue box around the column header that has "focus". At any given time, one link or button on a webpage has the state of focus, meaning that pressing the Enter key will activate that control. Having an obvious focus indicator is for accessibility purposes; it helps someone to use controls on a webpage without a mouse. The "tabindex" attribute described above allows the column headers to receive focus.

In table code generated by LibGuides, table headers have the class name "ck_border".

.ck_border:focus {outline:3px solid blue}

Table Sorting Code

The JavaScript code from W3Schools:

function sortTable(n) {
  var table, rows, switching, i, x, y, shouldSwitch, dir, switchcount = 0;
  table = document.getElementById("myTable");
  switching = true;
  //Set the sorting direction to ascending:
  dir = "asc"; 
  /*Make a loop that will continue until
  no switching has been done:*/
  while (switching) {
    //start by saying: no switching is done:
    switching = false;
    rows = table.getElementsByTagName("TR");
    /*Loop through all table rows (except the
    first, which contains table headers):*/
    for (i = 1; i < (rows.length - 1); i++) {
      //start by saying there should be no switching:
      shouldSwitch = false;
      /*Get the two elements you want to compare,
      one from current row and one from the next:*/
      x = rows[i].getElementsByTagName("TD")[n];
      y = rows[i + 1].getElementsByTagName("TD")[n];
      /*check if the two rows should switch place,
      based on the direction, asc or desc:*/
      if (dir == "asc") {
        if (x.innerHTML.toLowerCase() > y.innerHTML.toLowerCase()) {
          //if so, mark as a switch and break the loop:
          shouldSwitch= true;
          break;
        }
      } else if (dir == "desc") {
        if (x.innerHTML.toLowerCase() < y.innerHTML.toLowerCase()) {
          //if so, mark as a switch and break the loop:
          shouldSwitch= true;
          break;
        }
      }
    }
    if (shouldSwitch) {
      /*If a switch has been marked, make the switch
      and mark that a switch has been done:*/
      rows[i].parentNode.insertBefore(rows[i + 1], rows[i]);
      switching = true;
      //Each time a switch is done, increase this count by 1:
      switchcount ++;      
    } else {
      /*If no switching has been done AND the direction is "asc",
      set the direction to "desc" and run the while loop again.*/
      if (switchcount == 0 && dir == "asc") {
        dir = "desc";
        switching = true;
      }
    }
  }
}