How to scroll TABLE to particular TR programmatically

Assuming the project has a table with hundred’s of rows as a data set. And in a certain situation, an action in some other part of your page should result in showing a particular row in a table dynamically by using jquery.

How do scroll a table to particular tr?

Firstly, to demonstrate that, let’s create a template for the table filled with 100’s of rows.

https://gist.github.com/codewithsrini/818384d7d78769c8222cf7f6bf0e73cb

In the style css,

https://gist.github.com/codewithsrini/bba0f67f7837e32812193ef6a9aef8cb

In the actual javascript code.

https://gist.github.com/codewithsrini/84894f4d708dd4fa6dbc69546803b261

So, what are we trying to do actually?

Firstly, let’s analyse step by step.

var table = $('#tbl'),
  tableRow = '',
  tableContainer = $('#tableContainer'),
  link = $('.linkrow')
;

We are selecting #tbl from HTML DOM as a jQuery object and assigning it to a variable table, and #tableContainer similarly to a variable.

Also selecting ‘link-row’ to a variable.
for (var i=1; i<100; i++){
  tableRow += '<tr id="rowid'+ i +'"><td>This row is numbered as ' + i + '</td></tr>';
}

Using tableRow variable, we just iterate over 100 loops to populate our rows as HTML table row and table definition.

table.append(tableRow);

And then append our HTML table rows to the table.

link.click( function(e) {
  e.preventDefault();
  console.log('clicked');
  var rowIndex = $(this)[0].innerHTML,
    row;
  tableContainer.scrollTop(0);
 
  row = $('#rowid' + rowIndex);

  if(row.length) {
    console.log(row.offset().top);
    console.log(tableContainer.height()/2);

    tableContainer.scrollTop(row.offset().top - (tableContainer.height()/2))
  }

});

Similarly, listen to a click event for all the “link-row” jquery selector. And e.preventDefault() to stop ahref to refresh the page.

After a click is triggered, the link’s innerHTML is fetched to refer the row in a table and saved it in the row variable as a jquery object.

Finally, using the tableContainer scrollTop method in jQuery, the table can be scrolled by providing value as an argument.

So, the row object has an offset() method that holds the property for the top, left, bottom and right. Making use of the top property and dividing the tableContainer height to half. The row can be programmatically scrolled to view.

In conclusion, using a row’s offset and dividing the table’s outer container by half, we can scroll the table to a particular row.

ALSO READ  Learn to Build a Basic HTML5 CSS3 WebPage - HTML5 Introduction -Part 1 (in 10 mins)