How to handle DataTable specific events using jQuery DataTable plugin?


DataTables is a powerful jQuery plugin that enables developers to create feature-rich and interactive data tables in web applications. With its extensive set of options and functionalities, DataTables provides a flexible and customizable solution for displaying and manipulating tabular data.

One key aspect of enhancing the user experience and adding functionality to DataTables is by handling specific events triggered by the plugin. DataTables offers a wide range of events that allow developers to respond to user interactions, perform actions based on table changes, and customize behavior according to their requirements.

Basic Event Handling - Event Registration and Callbacks

To handle DataTable events, we need to register event handlers and provide callback functions that will be executed when the corresponding events are triggered. DataTables offers multiple approaches for event registration, giving developers flexibility in choosing the most suitable method based on their requirements.

Using the On() Method

The on() method in DataTables allows us to register event handlers for specific DataTable events. It provides a convenient way to bind callback functions to events and offers flexibility in event delegation and dynamic event handling.

Example 

Here's an example of registering an event handler for the draw.dt event using the on() method −

<!DOCTYPE html>
<html>
<head>
   <title>DataTables Event Handling Example</title>
   <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.25/css/jquery.dataTables.min.css">
</head>
<body>
   <table id="myTable" class="display" style="width:100%">
      <thead>
         <tr>
            <th>Name</th>
            <th>Position</th>
            <th>Office</th>
            <th>Age</th>
            <th>Start date</th>
            <th>Salary</th>
         </tr>
      </thead>
      <tbody>
         <tr>
            <td>Tiger Nixon</td>
            <td>System Architect</td>
            <td>Edinburgh</td>
            <td>61</td>
            <td>2011/04/25</td>
            <td>$320,800</td>
         </tr>
         <tr>
            <td>Garrett Winters</td>
            <td>Accountant</td>
            <td>Tokyo</td>
            <td>63</td>
            <td>2011/07/25</td>
            <td>$170,750</td>
         </tr>
         <!-- More rows... -->
      </tbody>
   </table>
   <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
   <script src="https://cdn.datatables.net/1.10.25/js/jquery.dataTables.min.js"></script>
   <script>
      $(document).ready(function() {
         $('#myTable').DataTable().on('draw.dt', function() {
            console.log('Table redrawn!');
         });
      });
   </script>
</body>
</html>

In this example, we select the DataTable with the myTable ID and use the on() method to register a callback function for the draw.dt event. Whenever the table is redrawn, the callback function will be executed, logging the message "Table redrawn!" to the console.

Using the On() Method with Event Namespaces

Event namespaces provide a way to organize and manage multiple event handlers for the same event. By using namespaces, we can register multiple event handlers for a specific event and easily remove or manage them individually.

Example 

Here's an example of using event namespaces with the on() method −

<!DOCTYPE html>
<html>
<head>
   <title>DataTables Event Handling Example</title>
   <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.25/css/jquery.dataTables.min.css">
</head>
<body>
   <table id="myTable" class="display" style="width:100%">
      <thead>
         <tr>
            <th>Name</th>
            <th>Position</th>
            <th>Office</th>
            <th>Age</th>
            <th>Start date</th>
            <th>Salary</th>
         </tr>
      </thead>
      <tbody>
         <tr>
            <td>Tiger Nixon</td>
            <td>System Architect</td>
            <td>Edinburgh</td>
            <td>61</td>
            <td>2011/04/25</td>
            <td>$320,800</td>
         </tr>
         <tr>
            <td>Garrett Winters</td>
            <td>Accountant</td>
            <td>Tokyo</td>
            <td>63</td>
            <td>2011/07/25</td>
            <td>$170,750</td>
         </tr>
         <!-- More rows... -->
      </tbody>
   </table>
   <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
   <script src="https://cdn.datatables.net/1.10.25/js/jquery.dataTables.min.js"></script>
   <script>
      $(document).ready(function() {
         $('#myTable').DataTable().on(    'draw.customEvent', function() {
            console.log('Custom event triggered!');
         });
   
         // Trigger the custom event
         $('#myTable').DataTable().trigger('draw.customEvent');
      });
   </script>
</body>
</html>

In this example, we register two event handlers for the draw event, each with a different namespace. By specifying the namespace when registering the event handlers, we can easily manage and remove them later if needed.

Using the Event() Method

The event() method in DataTables provides a straightforward way to bind event handlers for DataTable events. It is a shorthand method that internally calls the on() method and simplifies event registration.

Example 

Here's an example of using the event() method to register an event handler for the draw.dt event −

<!DOCTYPE html>
<html>
<head>
   <title>DataTables Event Handling Example</title>
   <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.25/css/jquery.dataTables.min.css">
</head>
<body>
   <table id="myTable" class="display" style="width:100%">
      <thead>
         <tr>
            <th>Name</th>
            <th>Position</th>
            <th>Office</th>
            <th>Age</th>
            <th>Start date</th>
            <th>Salary</th>
         </tr>
      </thead>
      <tbody>
         <tr>
            <td>Tiger Nixon</td>
            <td>System Architect</td>
            <td>Edinburgh</td>
            <td>61</td>
            <td>2011/04/25</td>
            <td>$320,800</td>
         </tr>
         <tr>
            <td>Garrett Winters</td>
            <td>Accountant</td>
            <td>Tokyo</td>
            <td>63</td>
            <td>2011/07/25</td>
            <td>$170,750</td>
         </tr>
         <!-- More rows... -->
      </tbody>
   </table>   
   <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
   <script src="https://cdn.datatables.net/1.10.25/js/jquery.dataTables.min.js"></script>
   <script>
      $(document).ready(function() {
         $('#myTable').DataTable().event('draw.dt', function() {
            console.log('Draw event triggered!');
         });
   
         // Trigger the draw event
         $('#myTable').DataTable().draw();
      });
   </script>
</body>
</html>

In this example, we use the event() method to register a callback function for the draw event. The behavior is similar to using the on() method, but with a more concise syntax.

By utilizing these event registration methods, we can easily bind event handlers and respond to specific DataTable events.

Advanced Event Handling

Event Delegation

Event delegation is a technique in jQuery DataTables that allows you to handle events on dynamically added elements or elements that are not present in the DOM when the page is loaded. Instead of attaching an event handler directly to the target element, you attach it to a parent element that exists at the time of binding. This way, the event will be captured when it bubbles up to the parent element, even if the target element is added later.

To implement event delegation with jQuery DataTables, you can use the on() method along with event delegation syntax. The general syntax is as follows 

$(document).on('event', 'selector', handler);

Here's an example of using event delegation to handle the click event on a dynamically added button within a DataTable −

Example 

<!DOCTYPE html>
<html>
<head>
   <title>Event Delegation Example</title>
   <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
   <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.11.3/css/jquery.dataTables.min.css">
   <script src="https://cdn.datatables.net/1.11.3/js/jquery.dataTables.min.js"></script>
</head>
<body>
   <table id="myTable" class="display">
      <thead>
         <tr>
            <th>Name</th>
            <th>Action</th>
         </tr>
      </thead>
      <tbody>
         <tr>
            <td>John Doe</td>
            <td><button class="btn-delete">Delete</button></td>
         </tr>
      </tbody>
   </table>
   <script>
      $(document).on('click', '#myTable .btn-delete', function() {
         var data = $(this).closest('tr').find('td:first').text();
         console.log('Delete button clicked for:', data);
      });
   
      $(document).ready(function() {
         $('#myTable').DataTable();
      });
   </script>
</body>
</html>

In this example, the click event is delegated to the document element, but the event handler will only be executed when a .btn-delete button is clicked within the #myTable element. This allows you to handle events for dynamically generated buttons or buttons added after the initial page load.

Custom Event Triggers

Apart from handling built-in events, jQuery DataTables also allows you to create and trigger custom events. Custom events can be useful when you want to create custom functionality or communicate between different parts of your application.

To create a custom event, you can use the trigger() method provided by jQuery. The trigger() method allows you to manually trigger a specified event on a DataTable instance.

Example 

Here's an example of creating and triggering a custom event −

<!DOCTYPE html>
<html>
<head>
   <title>Custom Event Example</title>
   <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
   <script src="https://cdn.datatables.net/1.10.25/js/jquery.dataTables.min.js"></script>
   <script>
      $(document).ready(function() {
         // Create a custom event
         var customEvent = $.Event('customEvent');
   
         // Trigger the custom event on a DataTable instance
         $('#myTable').DataTable().trigger(customEvent);
   
         // Register a handler for the custom event
         $('#myTable').on('customEvent', function() {
         console.log('Custom event triggered!');
         });
      });
   </script>
</head>
<body>
   <table id="myTable">
      <thead>
         <tr>
            <th>Name</th>
            <th>Age</th>
         </tr>
      </thead>
      <tbody>
         <tr>
            <td>John</td>
            <td>25</td>
         </tr>
         <tr>
            <td>Jane</td>
            <td>30</td>
         </tr>
      </tbody>
   </table>
</body>
</html>

In this example, we create a custom event called customEvent using the $.Event() function. We then trigger the custom event on a DataTable instance using the trigger() method. Finally, we register a handler for the custom event using the on() method and log a message when the event is triggered.

Common DataTable Events and Use Cases

Sorting Events

The jQuery DataTable plugin provides several events related to sorting that you can use to customize the sorting behavior and perform additional actions −

order.dt: Triggered when the sorting order is changed.
$('#myTable').on('order.dt', function (e, settings) {
   // Code to handle sorting order change
});
preInit.dt: Triggered just before the DataTable is initialized.
$('#myTable').on('preInit.dt', function (e, settings) {
   // Code to modify initial sorting order programmatically
});
preDraw.dt: Triggered before the DataTable is redrawn due to sorting.
$('#myTable').on('preDraw.dt', function (e, settings) {
   // Code to perform pre-processing tasks or modifications
});
draw.dt: Triggered after the DataTable is redrawn due to sorting.
$('#myTable').on('draw.dt', function (e, settings) {
   // Code to perform actions after the table has been updated
});

Filtering Events

The jQuery DataTable plugin provides events related to filtering that allow you to customize the filtering behavior and perform additional actions −

search.dt: Triggered when the search term is changed or the table is filtered.
$('#myTable').on('search.dt', function (e, settings) {
   // Code to handle search term change or filtering
});
preXhr.dt: Triggered before an Ajax request is made for server-side processing.
$('#myTable').on('preXhr.dt', function (e, settings, data) {
   // Code to modify the data sent to the server
});
xhr.dt: Triggered when an Ajax request is completed for server-side processing.
$('#myTable').on('xhr.dt', function (e, settings, json) {
   // Code to handle the server response
});
preFilter.dt: Triggered before the table is filtered.
$('#myTable').on('preFilter.dt', function (e, settings) {
   // Code to perform pre-processing tasks or modifications
});
filter.dt: Triggered after the table is filtered.
$('#myTable').on('filter.dt', function (e, settings) {
   // Code to perform actions after the table has been filtered
});

Pagination Events

The jQuery DataTable plugin provides events related to pagination that allow you to customize the pagination behavior and perform additional actions 

page.dt: Triggered when the table page is changed.
$('#myTable').on('page.dt', function (e, settings) {
   // Code to handle page change event
});
length.dt: Triggered when the number of rows per page is changed.
$('#myTable').on('length.dt', function (e, settings, len) {
   // Code to handle row length change event
});
preXhr.dt: Triggered before an Ajax request is made for server-side processing.
$('#myTable').on('preXhr.dt', function (e, settings, data) {
   // Code to modify the data sent to the server
});
xhr.dt: Triggered when an Ajax request is completed for server-side processing.
$('#myTable').on('xhr.dt', function (e, settings, json) {
   // Code to handle the server response
});
draw.dt: Triggered after the table is redrawn, which includes pagination updates.
$('#myTable').on('draw.dt', function (e, settings) {
   // Code to perform actions after the table is redrawn
});

Conclusion

By understanding and effectively using these event handling techniques, you can create dynamic and interactive tables that meet your specific requirements. Remember to carefully consider the event types, choose the appropriate event handling approach, and utilize the available event data to manipulate and control your DataTables.

Updated on: 07-Aug-2023

350 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements