Reputation: 5736
I would like to have this little button, when you click on it, a new table row is added and using the jQuery to smoothly scroll to that newly added row.
I have created an example here http://jsfiddle.net/2EBNH/
Notice that this is a simplified version of my code. The real one allows the row to be added anywhere within the table (doesn't have to be at the last row), so dont simply tell me I can always scroll to the bottom.
But even just scrolling to the bottom, the code doesnt work. It works for the first 10 rows I assume, but the position/offset (I have tried both) seems not correct if you have more rows added.
To test it, just add more than 15 rows then you will see the result.
I notice that if you move the scrollbar to the top everytime after you clicked on the button, it seems to work somehow.
Thank you
Upvotes: 0
Views: 2126
Reputation: 6273
The reason why this isn't working is the following:
The position() method returns a relative distance to the top of the window. Since you have limited the size of the div, the distance to the top of the window is not necessarily what you want to measure it against, but you want to measure it against the offset it has against the div that contains it.
In other words: When the scroll is on top and you add a new element (which goes to the bottom), the offset/position against the window is the same as the amount of pixels you want to scroll, so it works then. However, if you are already scrolled to the bottom, the distance between the element and the top of the window is just around 100px (the height of the div), so it will scroll to 100px, meaning that if the scroll distance is larger than that, it will actually go up.
You might be interested in checking the ScrollTo jQuery plugin:
var rownum = 1;
$('input').click(function () {
$('table').append('<tr id=row-' + rownum + '><td>' + rownum + ': row</td></tr>');
$('#row-' + rownum).ScrollTo({
duration: 400,
easing: 'linear'
});
rownum++;
});
Here is your fiddle using the plugin
Here is a solution WITHOUT using the plugin (and here's the jsfiddle):
var rownum = 1;
$('input').click(function () {
$('table').append('<tr id=row-' + rownum + '><td>' + rownum + ': row</td></tr>');
var $row = $('#row-' + rownum);
var topOffset = $row.parent().parent().parent().scrollTop() + $row.position().top;
$('div').animate({scrollTop: topOffset + "px"}, 400);
rownum++;
});
Upvotes: 2