jquery datatables scroll to top when pages clicked from bottom

后端 未结 7 634
余生分开走
余生分开走 2021-01-02 17:13

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 lo

7条回答
  •  醉话见心
    2021-01-02 17:56

    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/

提交回复
热议问题