alicelieutier/smoothScroll

Back doesn't work

Closed this issue · 4 comments

When clicking back, the address bar is updated (hash part changes, as expected), but the page doesn't change. I've tried latest version of both FF and Chrome.

I am not sure I understand why it behaves like this.
Still, I have a workaround, which is to listen to hash changes, and scroll to the location the url is pointing to.
There are two side effects to this, one is nice, but the other one is pretty bad I think:

  • we have a smoothscroll on clicking back :)
  • the smoothscroll function is executed twice for every internal link click.

I'll try and read more about this tonight, to see if I can find a better solution.

Here is the patch described above:
Edit: No longer valid, see next comment.

diff --git a/smoothscroll.js b/smoothscroll.js
index 27014b9..283522d 100644
--- a/smoothscroll.js
+++ b/smoothscroll.js
@@ -58,6 +58,12 @@ document.addEventListener("DOMContentLoaded", function () {
             });
         });
     }
+    // Fix for "Back doesn't work" [https://github.com/alicelieutier/smoothScroll/issues/1]
+    // => if we are not where we should be, let's scroll there
+    // this is a workaround... I still need to understand why the back button doesn't take you back
+    window.onhashchange = function(){
+        smoothScroll(document.getElementById(window.location.href.split('#').pop()) || document.body, 500);
+    };
 });

 })();
\ No newline at end of file

Just fixed this issue.

The problem was that the hash was added to the url after the scroll. This way, the browser registered the last state before change of hash as the previous state. As the scroll is kept when you navigate back and forward, we were navigating back but the scroll position did not change.

I used the history API to solves this, so the hash is now added before the scroll, and the back button succesfully takes us where we were before clicking on the link (which can or can not be the exact place referenced in the url).

Thanks, it works great.

BTW, I tested it in IE9 and it doesn't work there. Doesn't break anything, but no smooth scroll. Not that I care, but I thought I'd mention it.

Yeah, I fixed this using the history API, and it is not supported by IE9... so it's either a buggy history or a smoothscroll in IE9. I'll leave it like this for now, but might change it if someone complains.