Sllix
Sllix

Reputation: 606

.scrollTop() in a div

I want to scroll to a position in a div, when returning back to the page of the div. So, when I click an item in a list, the id of that item is for example 223. When returning back to the page, scrollTop has to go to the same position as clicked before.

I save the id of the item in a cookie.

Here is my code:

$(function () {
    var id = $.cookie('LastPositionCookie');
    var rowPos = $("#" + id).position();

    if (rowPos != null) {
        $('#tableBodyRes').scrollTop(rowPos.top);
    }
    else {
        alert(id + " " + rowPos + " error.");
    }
});

The scroll works fine, but it scrolls from the top of the page, not from the div (tableBodyRes). How can I fix this?

EDIT: added a picture with information

enter image description here

Here you can see on the left my div with an overflow. And on the right the normal overflow of my browser. I need to go to the green item when I return to this page again.

Thanks

Upvotes: 1

Views: 1309

Answers (1)

DACrosby
DACrosby

Reputation: 11440

To scroll the page to the top of an element,

// Swap ...
$('#tableBodyRes').scrollTop(rowPos.top);

// With ...
$('body').scrollTop(rowPos.top);

EDIT

For future reference, the issue at hand is scrolling an inner element to a position relative to the parent element (parent has overflow:hidden;), not relative to the document itself.

The solution we came up with was to take the inner element's top position and subtract from that the top position of the parent element.

Relevant jQuery

var rowPos = $("#336").position();
var divPos = $("#tableBodyRes").position();

var newTop = rowPos.top - divPos.top;

$('#tableBodyRes').scrollTop(newTop);

HTML

<div id="tableBodyRes" class="tableBodyDiv clearfix">
    <table id="tableReservations">
        <tr id="335"><td>335</td></tr>
        <tr id="336"><td>336</td></tr>
        <tr id="337"><td>337</td></tr>
    </table>
</div>

And a jsFiddle for good measure.

Upvotes: 2

Related Questions