Custom Sorting Terms in the Canvas UI

ColinMurtaugh
Community Champion
2
1651


In our Canvas instance, we've created a few dozen terms so far, mostly via integration with our SIS.  Each year we add several more, and the list is getting out of hand.  Further complicating matters is the fact that the terms are sorted in a seemingly random order.  Finding the specific term you're looking for in this long, out-of-order list can be tricky.

Fortunately, our naming convention places the year first, followed by the name (e.g. "2016 Summer"). If we could just have these lists sorted by the term label, things would be much easier to find.

So, I wrote some custom Javascript that can be added to your pages via the Canvas Theme Editor to do just that.  If you want to use this code in your own Canvas instance, you can download it from GitHub and customize as needed.

Here's how it works:

First, we define two functions -- one to sort the term select list on the "Courses in this account" pages, and one to sort the term table on the root account's terms page.

function sortTermDropdown(){

  var termSelect = $('select[name="enrollment_term_id"]');

  var selectedOption = $(termSelect).val();

  var termSelectList = $('option', termSelect);

  var newList = termSelectList.sort(function(a,b){

    return (a.label >= b.label) ? -1 : 1;

  });

  $(termSelect).html(newList).val(selectedOption);

};

function sortTermTable(){

  var termRowList = $('table#terms tbody tr.term').get();

  var newList = termRowList.sort(function(a,b){

    var alabel = a.getElementsByClassName('name')[0].innerHTML;

    var blabel = b.getElementsByClassName('name')[0].innerHTML;

    return (alabel >= blabel) ? -1 : 1;

  });

  $('table#terms').children('tbody').append(newList);

};

Next, we have some code that gets run when the page first loads that checks to see if either the term drop-down list or the term HTML table is present on the page, and calls the appropriate sort function.

$(document).ready(function() {

  if ($('select[name="enrollment_term_id"]').length > 0) {

    sortTermDropdown();

  }

  if ($('table#terms').length > 0) {

    sortTermTable();

  }

});

Since all of this javascript will be included on every page in our Canvas instance, the conditionals above allow us to only run the sort functions when necessary, reducing the chance for errors and minimizing the impact on pages that don't have any term lists on them.

Finally, we've chosen to have our terms sorted in descending order; because our labels begin with the year, this puts the most recent (and most frequently used) terms at the top of the list.  If your labels would be better sorted in ascending order, all you need to do is change the 'return' lines in each of the functions above, swapping the '1' and '-1' values.

2 Comments