datatables

jquery datatables scroll to top when pages clicked from bottom


I am using a jQuery datatable with bottom pagination. When the pages are clicked from bottom , I want it to scroll it to top, so users do not have to manually do that for longer pages. I tried using dataTables_scrollBody, but it doesn't work properly

Here is my code:

oTable = $('#tTable').dataTable({
    "fnDrawCallback": function(o) {
        $('dataTables_scrollBody').scrollTop(0);
     }
});

The page scrolls to top only when you click first/last (which I think is default behaviour), but not with every page click.


Solution

  • 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/