简体   繁体   中英

Scroll table row to top of div by clicking the row

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!

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">

This helps you?

$('table tr').bind('click', function() {
   var s = $('table').position();
   $('div').scrollTop(s);
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM