Search code examples
javascriptjquerydatatable

Auto scroll following the selected row Datatable jquery


This is my Datatable:

Image 1

If I press the down arrow the scroll doesn't follow the focus of the table so I have to move manually the scroll to see it. How can I do this automatically?

Image 2

$(document).keydown(function(e) {
  if (e.keyCode == 40) { //arrow down
    if (tr.next().length) {
      table.$('tr.selected').removeClass('selected');
      tr.next().addClass('selected');
      tr = table.$('tr.selected');
    }
  }
  
  if (e.keyCode == 38) { // arrow up
    if (tr.prev().length) {
      table.$('tr.selected').removeClass('selected');
      tr.prev().addClass('selected');
      tr = table.$('tr.selected');
    }
  }
})

Solution

  • You can add the scroll logic in your code to get this.

     function scrollToRow(row) { 
            // Check if the row is not visible
            if (row.position().top < 0 || row.position().top > row.parent().height()) {
                // Scroll smoothly to the new row
                $(Your_dropdown_table).animate({ 
                    scrollTop: row.position().top
                }, 100);
            }
        }
    Hope it can help you.