Reputation: 24583
I am trying to autoscroll to an element in a flexbox container.
<div class="nav">
<div class="items">
<div ng-repeat="i in items" scroll-on-click>
{{i}} click me to scroll to me!
</div>
</div>
</div>
app.directive('scrollOnClick', function() {
return {
restrict: 'A',
link: function(scope, $element) {
$element.on('click', function() {
$(".items").animate({scrollTop: $element.offset().top}, "slow");
});
}
}
});
It scrolls to the top of the first item clicked, but after that it has a hard time scrolling. I have had something very similar in a non-flexbox container working.
Here is a plunk:
http://plnkr.co/edit/kq40NiTqBI81KlRJBLHu?p=preview
Any ideas?
Upvotes: 3
Views: 4629
Reputation: 2407
Use the offsetTop
property to capture the scroll value of embedded (non-root) DOM elements, like a flexbox. Good discussion here. I'm subtracting 10 to stop the divs from being cut off, do as you wish.
$(".items").animate({scrollTop: $element.prop('offsetTop') - 10}, "slow");
EDIT:
To handle a header or other element, flexbox or not, just subtract its height from scrollTo (assigning an id to the header):
$(".items")
.animate(
{
scrollTop: $('#' + id).prop('offsetTop') -
document.getElementById('header').offsetHeight -
10 // Store this as a .constant if it won't change
}, "slow");
Upvotes: 6