Events
It can often be useful to know when DataTables or one of its extensions has performed a particular operation, for example a page draw, so other dependent elements can be updated to take account of the change. To provide this ability, DataTables will fire custom DOM events which can be listened for, and then acted upon, using on() or one(), and listeners removed with off(). DataTables's custom events work in exactly the same way as standard DOM events, and allow event driven actions, which is particularly useful for plug-ins.
For a full list of the events that DataTables and its extensions will trigger, please refer to the event reference documentation.
Listening for events
As noted above, you can use the on() method to listen for events. on() has with provision for namespaces and multiple events.
For example, to listen for the draw event in a DataTable:
const table = new DataTable('#myTable');
table.on('draw', function () {
alert('Table redrawn');
});
Removing events
Event listeners can be removed with off(). It is important to remove events from objects which no longer exist (before they are destroyed) to allow the Javascript engine's garbage collector to release the memory allocated for the events and the objects it has attached to.
Further to this, a single event can be listened for with one(), where the event handler will be removed immediately after the event has been triggered for the first time.
Bubbling
As with typical DOM events, many (but not all) DataTables events bubble up through the document, so you can listen for events on other elements which are higher up the DOM tree. Please refer to the event reference documentation for which events bubble. Not all will, to help improve performance.
Event bubbling can be useful, for example, to know when a new DataTable has been created, which can be listened for using the init event, which can be done thus:
document
.querySelector('body')
.addEventListener('init', function (e, settings) {
var api = new DataTable.Api(settings);
console.log('New DataTable created:', api.table().node());
});
Similarly, this method could also be useful with the xhr event which will let you know what JSON data was returned from the server from the last DataTables initiated Ajax query.
A full list of the events that DataTables and its extensions can trigger is available in the event reference documentation.