Search code examples
jqueryscrollanchorgsap

Scrolling To An Anchor Point Multiple Times


I'm trying to write a small function, which uses GSAP to scroll to an anchor point after another animation is completed.

The problem I'm having, is that the script works perfectly the first time, scrolling to the correct position, but when the function is called a second time, the overflow is scrolled back to the top of the page.

As I understand it, this is because on the second call of the function, the offSet from the top of the overflowed element is 0, as it has already scrolled, and so this is the value it now scrolls to.

However, I cannot think of an elegant method to achieve the functionality I'm looking for, namely that no matter where the overflow is, whenever the scroll function is called, the overflow scrolls to the anchor point.

I've created a reduced example below. In the final example, the animation which precedes the scroll, will shift the relative position of the anchor point, which is why I set the distance variable when the function is called:

var body = $(document.body);
var e = window.event || e;

function scroll(e) {

  var distance =  $("#test").offset().top - $(".wrap").offset().top

  TweenMax.to($(".wrap"), 1, {
   scrollTo: {y:distance, autoKill: true},
   force3D: true
  })

};


$(body).on('click', '.click', function (e) {

 scroll();

});

I've also created a quick CodePen, so that people can see the problem in action:

http://codepen.io/OneManLaptop/pen/YNbXBX

(click scroll at the bottom and it should scroll to the H2 tag)

(the demo behaviour is that you click the scroll button and the overflow scrolls to the anchor, but when you click it a second time it scrolls back to the top of the page. The desired behaviour, is that no matter how many times you click the button or where the anchor is relative to the overflow window, the overflow will either not move - as it is already at the anchor point - or will scroll to find the new position of the anchor.

Thanks for any offered help. :)


Solution

  • Pete's example was easy to modify to be GSAP friendly:

    http://codepen.io/OneManLaptop/pen/NdVRGJ

    function scroll(e) {
    
      var test =  $("#test"),
      wrap = $(".wrap"),
      distance = test.offset().top - parseInt(test.css('margin-top'))  + wrap.scrollTop();
    
      TweenMax.to($(".wrap"), 1, {
        scrollTo: {y:distance, autoKill: true},
        force3D: true
      })
    
    };
    

    Cheers Pete. :)