Jump to content

Snippets/Sort table on reload

From mediawiki.org
How to use Snippets
List of Snippets
Sort table on reload
Language(s): JavaScript
Compatible with: unknown

To "re-sort" a table automatically on the client side as the page loads (as if the user had clicked the header), add the following snippet to add MediaWiki:Common.js. This code snippet below uses the first column to sort every table on a set of pages in ascending order (see Tablesorter documentation).

function isSortedTablePage() {
    return ( wgPageName == "Page_To_Sort"  || wgPageName == "Other_Page_To_Sort" );
}

jQuery( document ).ready( function( $ ) {
    // wrapped in "mw.loader.using" so this doesn't execute until Tablesorter has loaded
    mw.loader.using( 'jquery.tablesorter', function() {
        if( isSortedTablePage() ) $('table.sortable').tablesorter( {sortList: [ { 0: 'asc'} ]} )
        // or look for tables with an ID attribute of "sortMe" on any page
        // $( '#sortMe' ).tablesorter( {sortList: [ { 0: 'asc'} ]} )
    } );
} );

Note Note: Clicking on headers causes this to disrupt sorting. While it initially sorts in ascending order based on the clicked header, it fails to reverse the sorting direction when clicked again.