Reputation: 3696
I've created a horizontal list of elements. The list has a fixed width and scrolls on overflow. When a button is clicked a new element is added to this list and I'm trying to scroll the ul element to this newly created li element.
Here's the JQuery I'm using:
var ul = $('ul')
$('button').click(function() {
var li = $('<li></li>');
ul.append(li);
ul.stop().animate({
scrollLeft: li.offset().left
}, 2000);
});
Oddly if you start tracing the variables li.offset().left
stays pretty much the same value for the first few elements and the scrolling works fine until li.offset().left
becomes less than ul.scrollLeft()
max value.
You can see this here: http://jsfiddle.net/ePrwZ/16/
It appears what is going on is that li.offset().left
is tracking the position relative to the document when I need it relative to the parent ul element. But I can't just minus the parent offest due to the overflow. Any idea on how to calculate this?
Note: I would like to scroll to the specific element not just to the end of the ul.
Upvotes: 0
Views: 581
Reputation: 570
change to:
ul.stop().animate({
scrollLeft: li.position().left + ul.scrollLeft()
}, 2000);
You are looking for position() method, which returns relative position, instead of offset, which returns absolute (more proper - relative to the document) position, and add current scroll state (which affects the position reading)
Upvotes: 1