trex trex - 6 months ago 28
Javascript Question

How to highlight words in datatables on pagination event

I need to highlight multiple words inside datatables https://datatables.net/.

Currently, my script highlights words on the first page of the table.
Words on the second page are not highlighted when you go to that page first time. But they are highlighted if you go to another page and then get back to the second page once again. And so on. I know, the words on the second page are not highlighted first time because the pagination event callback function called asynchronously. How to highlight words from the

hilitWrdArray[]
array on the pagination event?

$(document).ready(function() {

var table = $('#example').DataTable( {
searchHighlight: true
} );

new $.fn.dataTable.FixedHeader( table, {
alwaysCloneTop: true
});

var hilitWrdArray = ["junior", "software", "chief", "regional", "specialist"];

var myHilitor = new Hilitor('#example');
myHilitor.apply(hilitWrdArray.join());

$('#example').on('page.dt', function () {
myHilitor.apply(hilitWrdArray.join());
}.bind(null, myHilitor, hilitWrdArray));
} );


Here is full code example:
http://jsfiddle.net/sergibondarenko/emp5gp6o/12/

Answer

mark.js is a text highlighter compatible with DataTables. Have a look at these two examples:

Usage is as simple as:

$(function() {

  // Initialize DataTables
  var table = $('.datatables-table').DataTable({});

  // Initialize mark.js on table "draw" (search)
  table.on('draw', function() {

    // Get context
    var tableContent = $(table.table().body());
    // Get keyword
    var keyword = table.search();
    // Remove previous marks
    tableContent.unmark();
    // Mark the new search keyword
    tableContent.mark(keyword);

  });

});

You can also keep track on this issue regarding a DataTables plugin for mark.js.