rwkiii rwkiii - 7 months ago 299
jQuery Question

How to maintain jQuery DataTables scroll position after .draw()

I am using jQuery Datatables plugin for a smal table (12 rows). Some

<input type="text" ...
fields allow editing. When the input field loses focus I need to validate its value and possibly change the field value. I haven't been able to get modified input field values to be recognized by DataTables without issuing a
afterwards, but this causes the table to scroll to the top of the table.

Is there a way of maintaining the current scroll position after issuing a .draw()?

$('#mytable').on('blur', 'input', function (e) {

var inputFieldId =;
var inputFieldVal = $(this).val();

{ ... perform validation of field value ... }



I saw someone trying to do the same thing I am and they indicated that the following code worked for them. This seems like a very simple way of accomplishing what I need, but I'm always getting scrollTop = 0 myself. Anyone see how I can get the row index of the currently selected row?

var scrollPos = $(".dataTables_scrollBody").scrollTop();


I don't think you can do that, but you can use the Callback function instead:

$(document).ready(function() {
    var selected = [];

        "processing": true,
        "serverSide": true,
        "ajax": "scripts/ids-arrays.php",
        "rowCallback": function( row, data ) {
            if ( $.inArray(data.DT_RowId, selected) !== -1 ) {

    $('#example tbody').on('click', 'tr', function () {
        var id =;
        var index = $.inArray(id, selected);

        if ( index === -1 ) {
            selected.push( id );
        } else {
            selected.splice( index, 1 );

    } );
} );

Ref :