0

Basically, I have a table that has many rows. What I want to do is scroll the row I click to the top of the div that encases the table.

Here is the StackOverflow question I started from: How to scroll table to particular tr programmatically

Basically, this person was able to make the table jump to the table row he wanted by manually putting the in nth-child number like so:

var s = $("table tbody > tr:nth-child(20)").position();
$( "div" ).scrollTop( s.top );

Here is the fiddle he worked on showing it working for manually setting the nth-child in the code: http://jsfiddle.net/4Z7Z9/

Here is how I changed the code:

function scrollThisToTop(row) {
    var s = $("table tbody > tr:nth-child(" + row + ")").position();
    $( "div" ).scrollTop( s.top );
}

Here is my fiddle I am working on: http://jsfiddle.net/4Z7Z9/210/

Any help greatly appreciated!

Disguy
  • 39
  • 6
  • Do you want it to be added to the top of the Div, or rather have the contents scroll so that it is at the (visible) top but not the actual top? – Cornelis Oct 31 '18 at 20:44
  • have the contents scroll so that whatever row was clicked is the first row visible – Disguy Oct 31 '18 at 20:49

2 Answers2

0

I was able to get it working in 3 simple steps. Checkout the solution in fiddle HERE

You will need to add on click functionality as well as and ID for your containing div.

The new Function:

function scrollThisToTop(row) {

  // Get the id of the row
  var myElement = row.id;

  // Get the variable for the top of the row
    var topPos = row.offsetTop;

  // The container div top to the row top
  document.getElementById('container').scrollTop = topPos;

}

On click functionality:

$('tr').on("click", function () {
    scrollThisToTop(this);
});

Div id:

<div id="container">
Cornelis
  • 1,065
  • 8
  • 23
0

This helps you?

$('table tr').bind('click', function() {
   var s = $('table').position();
   $('div').scrollTop(s);
});
Ciprian B
  • 510
  • 3
  • 7