0

I am working on a page right now in jQuery. My page contains a link and a form. Here is the behavior that I want:

When the user clicks on a link, the browser scrolls down to the form with an animation. Here is the code, and it works well:

$('#myLink').click(function(){
     $('body, html').stop().animate({scrollTop:$('#myForm').offset().top-20});
});

Now, what I want, is that when the user clicks on the previous history button (of his browser), the browser scrolls back up to the top of the page with an animation.

Here is the code that I use. At the beginning of the JS code, I do:

history.pushState({'myStatus':'init'},'init','');

Then, inside the click listener I added:

if(history.state.myStatus == 'init') history.pushState({myStatus:'form'},'','#form');

And then, the onpopstate:

window.onpopstate = function(){
    if(history.state.myStatus == 'init' ) $('html,body').animate({scrollTop:0});
};

This works quite well. The only problem that I have is that before the animation, the browser jumps up to the top, and I don't like it.

Is there a way to make it work better?

Thank you!

4br3mm0rd
  • 543
  • 3
  • 26
  • Have you considered using #target links to achieve this? Like [here](http://stackoverflow.com/questions/7717527/smooth-scrolling-when-clicking-an-anchor-link). – Lucas Lazaro Sep 14 '16 at 21:47
  • How will that help me with the previous button? This button is not a link in my page, but the previous button of the browser. – 4br3mm0rd Sep 14 '16 at 23:05
  • If you use target to trigger the first scroll animation your URL will change to /#myForm, when hitting the browser back button it will come back to /, and triggering the animation you desire. – Lucas Lazaro Sep 14 '16 at 23:30

0 Answers0