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!