3

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?

lostintranslation
  • 23,756
  • 50
  • 159
  • 262

1 Answers1

6

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

Working Plunker

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

Working Plunker

Community
  • 1
  • 1
Mitch Lillie
  • 2,217
  • 18
  • 25
  • That is working a bit better. However I am still having problems if I have flex'ed content above the scroll. See updated plunker: http://plnkr.co/edit/kq40NiTqBI81KlRJBLHu?p=preview. Since its flex'ed I don't really know how how to offset. – lostintranslation Apr 05 '16 at 00:22
  • Hi, see my edited answer above. Hope this works for you. – Mitch Lillie Apr 05 '16 at 17:03