Search code examples
jquerytablesorter

Trigger a sort on button click instead of full click with jQuery tablesorter?


I am using this jQuery tablesorter : https://mottie.github.io/tablesorter/docs/index.html. I intitialize the sorting like this:

$('.sortable').tablesorter();

My table looks like this:

<table class="sortable" id="list-users">
    <thead>
        <tr>
            <th>
                <div class="sorter"></div>
                ID
            </th>
            <th>
                <div class="sorter"></div>
                Name
            </th>
            <th>
                <div class="sorter"></div>
                Birth date
            </th>
        </tr>
    </thead>
    <tbody>
        <tr>
...

The default behaviour is the following: when I click on a th tag, the table is sorted according to the column. That's good.

But I want to trigger the event when I click on the div.sorter instead. Do someone knows how to do it? I tried this :

$('table').find('th:eq(columnNumber)').trigger('sort');

But that doesn't disable the default event of course, this is useful when you want to trigger the event out of the thead.

Thanks!


Solution

  • There's actually a configurable selector in this plugin that lets you define which element triggers the sorting. Here's an example from the project documentation. Applying it to your markup, it might look like:

    $(function() {
        // call the tablesorter plugin
        $(".sortable").tablesorter({
            selectorSort : 'div.sorter'
        });
    });