Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 615
user1652427 Avatar asked Jun 27 '13 14:06

user1652427


1 Answers

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

like image 177
davidkonrad Avatar answered Nov 05 '22 15:11

davidkonrad