### Initialize Tablesort Instances
Source: https://github.com/tristen/tablesort/blob/main/demo/index.md
Instantiate Tablesort for specific tables using their IDs. This example shows initialization for two tables and one that will handle events.
```javascript
new Tablesort(document.getElementById('defaulting'));
new Tablesort(document.getElementById('column-keys'));
var events = document.getElementById('event-table')
new Tablesort(events);
```
--------------------------------
### File Size Sort Extension Example
Source: https://context7.com/tristen/tablesort/llms.txt
This extension sorts file sizes with units including KB, MB, GB, TB and their binary equivalents (KiB, MiB, GiB, TiB). Include `tablesort.filesize.js` and initialize Tablesort on the table.
```html
Filename
Size
document.pdf
5.35 KB
video.mp4
1.2 GB
image.png
750 KiB
archive.zip
10 MB
```
--------------------------------
### Dot-Separated Values Sort Extension Example
Source: https://context7.com/tristen/tablesort/llms.txt
This extension sorts dot-separated numeric values like IP addresses and version numbers by comparing each segment numerically. Include `tablesort.dotsep.js` and initialize Tablesort on the table.
```html
Package
Version
IP Address
React
18.2.0
192.168.1.1
Vue
3.3.4
10.0.0.1
Angular
16.1.0
172.16.0.1
```
--------------------------------
### Date Sort Extension Example
Source: https://context7.com/tristen/tablesort/llms.txt
This extension sorts date values in various formats, including dd/mm/yy, dd-mm-yyyy, and dates with month or day names. Include `tablesort.date.js` and initialize Tablesort on the table.
```html
Event
Date
Meeting
15/03/2023
Conference
Mon, 20 Jan 2023
Workshop
5-12-2022
```
--------------------------------
### Number Sort Extension Example
Source: https://context7.com/tristen/tablesort/llms.txt
This extension sorts numeric values, including integers, decimals, negative numbers, percentages, and currency values with various prefixes and suffixes. Include `tablesort.number.js` and initialize Tablesort on the table.
```html
Item
Price
Quantity
Widget A
$1,234.56
100
Widget B
$99.99
-50
Widget C
€2,500.00
75%
```
--------------------------------
### Month Name Sort Extension Example
Source: https://context7.com/tristen/tablesort/llms.txt
This extension sorts columns containing full month names (January, February, etc.) in chronological order. Include `tablesort.monthname.js` and initialize Tablesort on the table.
```html
Report
Month
Q1 Report
March
Q2 Report
January
Q3 Report
September
```
--------------------------------
### Event Listeners for Sorting Lifecycle
Source: https://context7.com/tristen/tablesort/llms.txt
Tablesort dispatches `beforeSort` and `afterSort` events on the table element. Use these events to hook into the sorting process, for example, to show loading indicators.
```javascript
const table = document.getElementById('my-table');
const sort = new Tablesort(table);
// Listen for sort events
table.addEventListener('beforeSort', function() {
console.log('Sorting is about to begin...');
// Show loading indicator, disable UI, etc.
});
table.addEventListener('afterSort', function() {
console.log('Sorting complete!');
// Hide loading indicator, update UI state, etc.
});
```
--------------------------------
### Internationalized String Sort Extension Example
Source: https://context7.com/tristen/tablesort/llms.txt
This extension uses the JavaScript Intl.Collator API for locale-aware string comparison, properly handling accented characters and language-specific sorting rules. Include `tablesort.intl.js` and initialize Tablesort on the table with `data-sort-method="intl"`.
```html
Name
Country
Müller
Germany
Muller
France
Möller
Sweden
```
--------------------------------
### Serve Tablesort Demo Locally
Source: https://github.com/tristen/tablesort/blob/main/README.md
Run the Jekyll server to view the Tablesort demo locally.
```sh
jekyll serve
```
--------------------------------
### Initialization with Options
Source: https://context7.com/tristen/tablesort/llms.txt
Customize sorting behavior by passing a configuration object. Options include setting the default sort order to descending or specifying a custom data attribute for sort values.
```javascript
const table = document.getElementById('my-table');
// Sort descending by default
const sort = new Tablesort(table, {
descending: true
});
// Use custom data attribute for sort values
const sortWithCustomAttr = new Tablesort(table, {
sortAttribute: 'data-custom-sort-val'
});
```
--------------------------------
### Import and Initialize Tablesort in Node.js/Browserify
Source: https://github.com/tristen/tablesort/blob/main/README.md
Import the tablesort library and initialize it with an element and optional options.
```javascript
import tablesort from 'tablesort';
tablesort(el, options);
```
--------------------------------
### Run Tablesort Tests
Source: https://github.com/tristen/tablesort/blob/main/README.md
Execute the test suite for Tablesort using npm.
```sh
npm test
```
--------------------------------
### Include Tablesort and Sort Types in HTML
Source: https://github.com/tristen/tablesort/blob/main/README.md
Include the main Tablesort script and any desired sort type scripts in your HTML. Then, initialize Tablesort by passing the ID of the table element.
```html
```
--------------------------------
### Initialize Analytics
Source: https://github.com/tristen/tablesort/blob/main/demo/_layouts/default.html
This script initializes the analytics object and defines its methods. It's designed to be included in your HTML to load the analytics script.
```javascript
var analytics=analytics||[];(function(){var e=["identify","track","trackLink","trackForm","trackClick","trackSubmit","page","pageview","ab","alias","ready","group"];var t=function(e){return function(){analytics.push([e].concat(Array.prototype.slice.call(arguments,0)))}};for(var n=0;n` element.
```javascript
tableSortDotsep = document.getElementById('sort-dotsep');
new Tablesort(tableSortDotsep);
```
--------------------------------
### Basic HTML Table Initialization
Source: https://context7.com/tristen/tablesort/llms.txt
Initialize Tablesort on an HTML table using script tags. Ensure the table has thead and tbody elements. The tablesort.min.js and tablesort.number.js files are required.
```html
Name
Age
City
Alice
28
New York
Bob
34
Chicago
Charlie
22
Boston
```
--------------------------------
### Initialize Tablesort
Source: https://github.com/tristen/tablesort/blob/main/test/index.html
Basic initialization of Tablesort on an HTML table element. No special configuration is needed for default ascending sort.
```javascript
table = document.getElementById('sort');
new Tablesort(table);
```
--------------------------------
### Initialize Tablesort with Custom Column Keys
Source: https://github.com/tristen/tablesort/blob/main/test/index.html
Initialize Tablesort. To specify custom sort keys for a column, add the `data-sort-keys` attribute to the `
` element.
```javascript
tableSortColumnKeys = document.getElementById('sort-column-keys');
new Tablesort(tableSortColumnKeys);
```
--------------------------------
### Initialize Tablesort with Descending Order
Source: https://github.com/tristen/tablesort/blob/main/test/index.html
Initialize Tablesort with the `descending: true` option to sort the table in descending order by default.
```javascript
tableDescend = document.getElementById('sort-descend');
new Tablesort(tableDescend, { descending: true });
```
--------------------------------
### Initialize Tablesort
Source: https://github.com/tristen/tablesort/blob/main/demo/_includes/header.html
Instantiate Tablesort by providing the ID of the HTML table element you want to sort. Ensure the table has an ID attribute.
```javascript
new Tablesort(document.getElementById('sort'));
```
--------------------------------
### Module Import and Initialization
Source: https://context7.com/tristen/tablesort/llms.txt
Import Tablesort as an ES module for use in modern JavaScript applications. It can be called with or without the 'new' keyword.
```javascript
import Tablesort from 'tablesort';
// Initialize on a table element
const table = document.getElementById('my-table');
const sort = Tablesort(table);
// Or with the new keyword
const sort = new Tablesort(table);
```
--------------------------------
### Initialize Tablesort with Column Exclusion
Source: https://github.com/tristen/tablesort/blob/main/test/index.html
Initialize Tablesort. By default, all columns are sortable. To exclude a column, add the `data-sort-method='none'` attribute to the `
` element.
```javascript
tableExclude = document.getElementById('sort-exclude');
new Tablesort(tableExclude);
```
--------------------------------
### Initialize Tablesort with Custom Sort Attribute
Source: https://github.com/tristen/tablesort/blob/main/test/index.html
Initialize Tablesort with a custom sort attribute. Use the `sortAttribute` option to specify which attribute to use for sorting.
```javascript
tableSortCustomAttr = document.getElementById('sort-custom-attribute');
new Tablesort(tableSortCustomAttr, { sortAttribute: "data-realname" });
```
--------------------------------
### Handle Sorting Events
Source: https://github.com/tristen/tablesort/blob/main/demo/index.md
Attach custom event listeners for 'beforeSort' and 'afterSort' events on a Tablesort instance. Ensure the 'addEvent' helper function is defined.
```javascript
addEvent(events, 'beforeSort', function(e) {
alert('Table is about to be sorted!');
});
addEvent(events, 'afterSort', function(e) {
alert('Table sorted!');
});
```
--------------------------------
### Add and Remove Table Rows Dynamically
Source: https://github.com/tristen/tablesort/blob/main/demo/index.md
This script demonstrates how to dynamically add or remove rows from a table and then refresh the Tablesort instance to recognize the changes. It uses a predefined array of trumpeters for adding new rows.
```javascript
var trumpeters = [
{
"name": "Miles Davis",
"born": 1926
},
{
"name": "Dizzy Gillespie",
"born": 1917
},
{
"name": "Wynton Marsalis",
"born": 1961
},
{
"name": "Tom Harell",
"born": 1946
},
{
"name": "Roy Hargrove",
"born": 1969
},
{
"name": "Chet Baker",
"born": 1929
},
{
"name": "Nicholas Payton",
"born": 1973
},
{
"name": "Wallace Roney",
"born": 1960
},
{
"name": "Rex Stewart",
"born": 1907
},
{
"name": "Tim Hagans",
"born": 1954
},
{
"name": "Roy Eldridge",
"born": 1911
},
{
"name": "Freddie Hubbard",
"born": 1938
}
]
var r = document.getElementById('refresh-table');
var add = document.getElementById('add');
var remove = document.getElementById('remove');
var refresh = new Tablesort(r);
function cancel(event) {
(event.preventDefault) ? event.preventDefault() : event.returnValue = false;
(event.stopPropagation) ? event.stopPropagation() : event.cancelBubble = true;
}
function addEvent(object, event, method) {
if (object.attachEvent) {
object['e' + event + method] = method;
object[event + method] = function(){object['e' + event + method](window.event);};
object.attachEvent('on' + event, object[event + method]);
} else {
object.addEventListener(event, method, false);
}
};
addEvent(add, 'click', function(e) {
cancel(e);
var player = trumpeters[Math.floor(Math.random() * trumpeters.length)];
var rowCount = r.rows.length;
var row = r.insertRow(rowCount);
var cellName = row.insertCell(0);
cellName.innerHTML = player.name;
var cellBorn = row.insertCell(1);
cellBorn.innerHTML = player.born;
refresh.refresh();
});
addEvent(remove, 'click', function(e) {
cancel(e);
var rowCount = r.rows.length;
if (rowCount === 2) return;
r.deleteRow(rowCount - 1);
});
```
--------------------------------
### Default Sort Initialization
Source: https://github.com/tristen/tablesort/blob/main/demo/index.md
To automatically sort a table when a Tablesort instance is created, add the 'data-sort-default' attribute to the header cell.
```html
Born
```
--------------------------------
### Handle Tablesort Events
Source: https://github.com/tristen/tablesort/blob/main/demo/index.md
Attach event listeners to the table element to react to 'beforeSort' and 'afterSort' events. These events fire before and after the table is sorted, respectively.
```javascript
var table = document.getElementById('table-id');
var sort = new Tablesort(table);
table.addEventListener('beforeSort', function() {
alert('Table is about to be sorted!');
});
table.addEventListener('afterSort', function() {
alert('Table sorted!');
});
```
--------------------------------
### Default Sort Column Configuration
Source: https://context7.com/tristen/tablesort/llms.txt
Set a column to be sorted automatically on initialization by adding the `data-sort-default` attribute to the header cell.
```html
Name
Born
Roy Eldridge
1911
Tim Hagans
1954
Freddie Hubbard
1938
```
--------------------------------
### Sorting with Column Keys (Colspan Support)
Source: https://context7.com/tristen/tablesort/llms.txt
Use `data-sort-column-key` on `
` and `
` elements to link headers to specific cells in tables with `colspan`. All linked elements must share the same key value.
```html
Product
Price
Apples
Sale!
20
Bread
Out of stock
10
Radishes
In Stock!
30
```
--------------------------------
### Initialize Tablesort for Row Sorting
Source: https://github.com/tristen/tablesort/blob/main/test/index.html
Initialize Tablesort. To sort rows, add the `data-sort-row='true'` attribute to the `
` element.
```javascript
tableSortRowSet = document.getElementById('sort-row-set');
new Tablesort(tableSortRowSet);
```
```javascript
tableSortRowAuto = document.getElementById('sort-row-auto');
new Tablesort(tableSortRowAuto);
```
--------------------------------
### Helper Function for Event Binding
Source: https://github.com/tristen/tablesort/blob/main/demo/index.md
A utility function to add event listeners to DOM elements, supporting both modern browsers (addEventListener) and older IE versions (attachEvent).
```javascript
function addEvent(object, event, method) {
if (object.attachEvent) {
object['e' + event + method] = method;
object[event + method] = function(){object['e' + event + method](window.event);};
object.attachEvent('on' + event, object[event + method]);
} else {
object.addEventListener(event, method, false);
}
};
```
--------------------------------
### Initialize Tablesort with Default Sort Column
Source: https://github.com/tristen/tablesort/blob/main/test/index.html
Initialize Tablesort. To set a default sort column, add the `data-sort-default='true'` attribute to the `
` element.
```javascript
tableDefault = document.getElementById('sort-default');
new Tablesort(tableDefault);
```
--------------------------------
### Sorting by Column Keys
Source: https://github.com/tristen/tablesort/blob/main/demo/index.md
Use 'data-sort-column-key' to explicitly link a header to specific cells for sorting, useful for tables with colspans or when data is not in a direct column.
```html
Product
Price
Apples
Sale!
20
Bread
Out of stock
10
Radishes
In Stock!
30
```
--------------------------------
### Extend Tablesort with Custom Sort Functionality
Source: https://github.com/tristen/tablesort/blob/main/README.md
Extend Tablesort to add custom sorting logic. Define a regular expression to test table cell items and a comparison function for sorting.
```javascript
Tablesort.extend('name', item => {
// Regular expression to test against.
// `item` is a table value to evaluate.
return /foo/.test(item);
}, (a, b) => {
// Custom sort functionality goes here.
// e.g var n = (a > b) ? -1 : 1;
return n;
});
```
--------------------------------
### Helper Function to Cancel Event Propagation
Source: https://github.com/tristen/tablesort/blob/main/demo/index.md
A utility function to prevent default browser actions and stop event propagation, ensuring custom event handling takes precedence.
```javascript
function cancel(event) {
(event.preventDefault) ? event.preventDefault() : event.returnValue = false;
(event.stopPropagation) ? event.stopPropagation() : event.cancelBubble = true;
}
```
--------------------------------
### Extend Tablesort with Custom Sort Types
Source: https://context7.com/tristen/tablesort/llms.txt
Register custom sort types with a name, pattern detection, and comparison function. Use this for data formats not automatically supported by Tablesort.
```javascript
Tablesort.extend('hexcolor', function(item) {
// Pattern detection: returns true if item looks like a hex color
return /^#[0-9A-Fa-f]{6}$/.test(item);
}, function(a, b) {
// Sort function: convert hex to decimal for comparison
const numA = parseInt(a.slice(1), 16);
const numB = parseInt(b.slice(1), 16);
return numB - numA;
});
```
```javascript
// Custom sort for percentage values
Tablesort.extend('percentage', function(item) {
return /^\d+(\.\d+)?%\$/.test(item);
}, function(a, b) {
const numA = parseFloat(a);
const numB = parseFloat(b);
return numB - numA;
});
```
```javascript
// Usage
new Tablesort(document.getElementById('my-table'));
```
--------------------------------
### Specify Sort Method for a Column
Source: https://github.com/tristen/tablesort/blob/main/demo/index.md
Force a specific sorting method for a column by adding the 'data-sort-method' attribute to the table header (th). The attribute value should match the name of a registered sort function.
```html
Number
Version
1
3.7.2004
2
1.08.2013
```
--------------------------------
### Reverse Sort Order for Specific Columns
Source: https://context7.com/tristen/tablesort/llms.txt
Make a specific column sort in the opposite direction of the default by adding the `data-sort-reverse` attribute to its header cell.
```html
Name
Score
Alice
95
Bob
87
```
--------------------------------
### Specify Header Row in Multi-Row Thead
Source: https://context7.com/tristen/tablesort/llms.txt
For tables with multiple header rows, designate the sortable row by adding `data-sort-method='thead'` to the desired `
` element. Other header rows will not be sortable.
```html
Sortable Header
Another Sortable
Sub-header (not sortable)
Another sub-header
Data 1
Value A
Data 2
Value B
```
--------------------------------
### Specify Table Heading Row for Sorting
Source: https://github.com/tristen/tablesort/blob/main/demo/index.md
If your table has multiple heading rows, designate the row that should enable sorting by adding the 'data-sort-method="thead"' attribute to the desired 'tr' element.
```html
Sort Row
Not Sort Row
2
1
3
```
--------------------------------
### Default CSS for Tablesort Sort Indicators
Source: https://context7.com/tristen/tablesort/llms.txt
Includes default CSS styles for sort indicators using ARIA attributes. This styling makes sortable headers visually distinct and shows sort direction arrows.
```css
/* Make sortable headers show pointer cursor */
th[role=columnheader]:not([data-sort-method='none']) {
cursor: pointer;
}
```
```css
/* Sort direction indicator arrow */
th[role=columnheader]:not([data-sort-method='none']):after {
content: '';
float: right;
margin-top: 7px;
border-width: 0 4px 4px;
border-style: solid;
border-color: #404040 transparent;
visibility: hidden;
opacity: 0;
user-select: none;
}
```
```css
/* Ascending sort arrow (points up) */
th[aria-sort=ascending]:not([data-sort-method='none']):after {
border-bottom: none;
border-width: 4px 4px 0;
}
```
```css
/* Show arrow on sorted column */
th[aria-sort]:not([data-sort-method='none']):after {
visibility: visible;
opacity: 0.4;
}
```
```css
/* Show arrow on hover/focus */
th[role=columnheader]:not([data-sort-method='none']):focus:after,
th[role=columnheader]:not([data-sort-method='none']):hover:after {
visibility: visible;
opacity: 1;
}
```
--------------------------------
### Use Custom Sort Attribute
Source: https://github.com/tristen/tablesort/blob/main/demo/index.md
Configure Tablesort to use a custom data attribute for sorting values instead of the default 'data-sort' by setting the 'sortAttribute' option.
```javascript
var table = document.getElementById('table-id');
var sort = new Tablesort(table, { sortAttribute: 'data-custom-sort-val'});
```
--------------------------------
### Refresh Tablesort Instance
Source: https://github.com/tristen/tablesort/blob/main/test/index.html
Refresh the Tablesort instance after dynamically adding or removing rows. This ensures the sorting is updated correctly.
```javascript
var refresh = new Tablesort(tableRefresh);
var rowCount = tableRefresh.rows.length;
var row = tableRefresh.insertRow(rowCount);
var cellName = row.insertCell(0);
cellName.innerHTML = 0;
refresh.refresh();
```
--------------------------------
### Refresh Sort After Appending Data
Source: https://github.com/tristen/tablesort/blob/main/demo/index.md
After adding new data to the table, call the 'refresh' method on the Tablesort instance to re-initialize sorting for the updated table content.
```javascript
var table = document.getElementById('table-id');
var sort = new Tablesort(table);
// Make some Ajax request to fetch new data and on success:
sort.refresh();
```
--------------------------------
### Exclude Columns from Sorting
Source: https://context7.com/tristen/tablesort/llms.txt
Prevent specific columns from being sortable by adding `data-sort-method="none"` to the header cell. These columns will not respond to clicks.
```html
Actions
Name
Date
Alice
2023-01-15
Bob
2023-02-20
```
--------------------------------
### Exclude Column from Sorting
Source: https://github.com/tristen/tablesort/blob/main/demo/index.md
Add the 'data-sort-method="none"' attribute to a table header (th) or a table row (tr) to prevent it from being sorted.
```html
Name
1
Gonzo the Great
12-2-70
Radishes
$0.63
```
--------------------------------
### Custom Sort Values with data-sort Attribute
Source: https://context7.com/tristen/tablesort/llms.txt
Use the `data-sort` attribute on `
` elements to provide a custom sorting value, overriding the visible text. This is useful for sorting formatted dates or numbers.
```html
Event
Timestamp
Login
01/08/13 @ 8:47:18am EST
Logout
3/7/2004 @ 9:24:45 EST
Update
01/01/15 @ 12:00:00am EST
```
--------------------------------
### Override Sort Data with data-sort Attribute
Source: https://github.com/tristen/tablesort/blob/main/demo/index.md
Use the 'data-sort' attribute on table cells to provide specific values for sorting, overriding the cell's inner text. This is useful for normalizing data.
```html
1
01/08/13 @ 8:47:18am EST
2
3/7/2004 @ 9:24:45 EST
```
--------------------------------
### Exclude Rows from Sorting
Source: https://context7.com/tristen/tablesort/llms.txt
Add `data-sort-method='none'` to a `
` element to prevent it from being reordered during sorting. This keeps the row in its original position.
```html
#
Name
Price
-
Total
$100.00
1
Apples
$25.00
2
Oranges
$75.00
```
=== COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.