Want to fire a custom event when trying to sort in Datatables

14,616

Very easy. You just unbind the click.DT handler and add your own. You dont have to disable sorting.

example

<table id="example">
<thead>
   <th id="id">ID</th>
   <th id="username">Username</th>
</thead>
<tbody>
    <tr><td>1</td><td>A test</td></tr>
    <tr><td>2</td><td>B test</td></tr>
    </tbody>       
</table>

javascript

$(document).ready(function(){
    //init datatables
    var table = $('#example').dataTable();

    //unbind sort event, prevent sorting when header is clicked
    $('#example th').unbind('click.DT');

    //create your own click handler for the header
    $('#example th').click(function(e) {
        alert('Header '+$(this).attr('id')+' clicked');
        //here you can trigger a custom event
    });

    //if you afterwards want to restablish sorting triggered by a click event 
    //here header "username" from example above
    table.fnSortListener(document.getElementById('username'), 1);
});

Note : There is no dedicated "sort"-event in datatables. Allan Jardine mention it may come in a future version 2. http://datatables.net/forums/discussion/5141/capturing-sort-event-on-table-heading/p1

Share:
14,616
user1652427
Author by

user1652427

Updated on June 18, 2022

Comments

  • user1652427
    user1652427 almost 2 years

    When the user clicks on a column header to sort, I want to fire my own event. I DO NOT want it to sort. I've been doing research, and don't see a good way to do this.

    I can bind on the sort event to do my own stuff, but the sort still happens. I don't want this. If I disable sorting, then the sort event never fires, so this does not work either.

    I could disable sort and then try and capture click events on the header, but I was hoping there would be a better way to do this. Anyone have any ideas?