jquery datatables scroll to top when pages clicked from bottom

This worked out for me.

$(document).ready(function() {
    var oldStart = 0;
    $('#example').dataTable({
        "bJQueryUI": true,
        "sPaginationType": "full_numbers",
        "fnDrawCallback": function (o) {
            if ( o._iDisplayStart != oldStart ) {
                var targetOffset = $('#example').offset().top;
                $('html,body').animate({scrollTop: targetOffset}, 500);
                oldStart = o._iDisplayStart;
            }
        }
    });
} );

I'm also using datatables and Allan's solution (found here) worked perfectly for me.

$(document).ready(function() {
    var oldStart = 0;
    $('#example').dataTable({
        "bJQueryUI": true,
        "sPaginationType": "full_numbers",
        "fnDrawCallback": function (o) {
        if ( o._iDisplayStart != oldStart ) {
            var targetOffset = $('#example').offset().top;
            $('html,body').animate({scrollTop: targetOffset}, 500);
            oldStart = o._iDisplayStart;
        }
      }
    });
} );

Since Datatables 1.10 there is this page event https://datatables.net/reference/event/page

So one can use

$('#example_table').on( 'page.dt', function () {
    $('html, body').animate({
        scrollTop: 0
    }, 300);
} );

Demo: https://jsfiddle.net/mcyhqrdx/


Update. The original answer was targeting 1.9.x. In dataTables 1.10.x it is much easier :

table.on('page.dt', function() {
  $('html, body').animate({
    scrollTop: $(".dataTables_wrapper").offset().top
  }, 'slow');
});

demo -> http://jsfiddle.net/wq853akd/

Also, if you're using the bootstrap version of datatables, you may notice that when using the fix, the page actually scrolls back down after scrolling to the top. This is because it is focusing on the clicked button as per this datatables.net thread. You can fix this by simply focusing on the table header after the animate call, like so:

table.on('page.dt', function() {
  $('html, body').animate({
    scrollTop: $(".dataTables_wrapper").offset().top
  }, 'slow');

  $('thead tr th:first-child').focus().blur();
});

Original Answer

You should target .dataTables_wrapper and attach the event to .paginate_button instead. Here with a nice little animation :

function paginateScroll() {
    $('html, body').animate({
       scrollTop: $(".dataTables_wrapper").offset().top
    }, 100);
    console.log('pagination button clicked'); //remove after test
    $(".paginate_button").unbind('click', paginateScroll);
    $(".paginate_button").bind('click', paginateScroll);
}
paginateScroll();

see fiddle -> http://jsfiddle.net/EjbEJ/

Tags:

Datatables