Search code examples
javascriptjquerynicescroll

Auto scroll to last row of table


I'm working on a simple table using nicescroll plugin.

On load the table auto scroll to bottom, also, I added a button which adds a new row and scroll to bottom too.

my problem is when I added a new input field that generate a rows base from user input, it wont scroll to the last row, some times it bounce in the middle.

Hope you help me.

Thanks

here is my sample code

// add scroll

$('tbody').niceScroll({autohidemode: false});

// add 1 row
$('button').click(function(){

        var rowCount = $('table > tbody tr').length + 1;

    $('tbody').append('<tr><td>item'+ rowCount +'</td><td>items</td><td>items</td><td>items</td><td>items</td></tr>');

  $('tbody').animate({
  scrollTop: $('tbody').get(0).scrollHeight}, 2000);

});

// scroll to bottom on load
$('tbody').animate({
  scrollTop: $('tbody').get(0).scrollHeight}, 2000);

// generate rows
$('input').keyup(function(){
  $('table tbody tr').remove();
  $('tbody').animate({
  scrollTop: $('tbody').get(0).scrollHeight}, 2000);

  var rowCount = $('table > tbody tr').length + 1;  
    for(var i = 1; i <= $(this).val(); i++ ){
     $('tbody').append('<tr><td>item'+ i +'</td><td>items</td><td>items</td><td>items</td><td>items</td></tr>'); 
    }

});

// clear value on input field
$('input').click(function(){
    $(this).val('');
});

Solution

  • Only change a bit of your js code

    Way 1

    ...
    // generate rows
    $('input').keyup(function(){
      // Clean table
      $('table tbody tr').remove();
      // Add new rows
      var rowCount = $('table > tbody tr').length + 1;  
      for(var i = 1; i <= $(this).val(); i++ ){
         $('tbody').append('<tr><td>item'+ i +'</td><td>items</td><td>items</td><td>items</td><td>items</td></tr>'); 
      }
      // Then stop previous anim with clean anim queue (added by every key typed in input) and finally add new anim
      $('tbody').stop(true, false).animate({
          scrollTop: $('tbody').get(0).scrollHeight}, 2000);
      });
    });
    ...
    

    Way 2

    ...
    // generate rows
    $('input').keyup(function(){
      $('table tbody tr').remove();  
      var rowCount = $('table > tbody tr').length + 1;  
      for(var i = 1; i <= $(this).val(); i++ ){
        $('tbody').append('<tr><td>item'+ i +'</td><td>items</td><td>items</td><td>items</td><td>items</td></tr>'); 
        // Animate during row adding  
        $('tbody').stop().animate({scrollTop: $('tbody').get(0).scrollHeight}, 2000);      
      }
    });