Skip to content

Commit

Permalink
Fix smooth-scroll to not break the back button
Browse files Browse the repository at this point in the history
In the Beginning, "Community" in the navbar on the homepage was a normal
link, and clicking it would take you to the Community section and
highlight the heading, and the browser Back button would take you back
to your scroll position at the top of the page where the navbar was.

Then I added smooth-scrolling so that when you click "Community" in the
navbar it would smoothly scroll down to the Community heading, and
highlight it. Problem: if you then hit the browser Back button, the
heading highlight would vanish but you would stay in place, rather than
the expected behavior of going back to the scroll position at the top of
the page where you clicked on the navbar.

Now I'm finally fixing that by doing history.pushState():
  https://developer.mozilla.org/en-US/docs/Web/API/History_API
(falling back to the old technique if unavailable)

Of course the web platform sucks so we have to contend with:
  whatwg/html#639
  • Loading branch information
laughinghan committed Apr 13, 2016
1 parent ba8c4ca commit 8d89f89
Showing 1 changed file with 11 additions and 2 deletions.
13 changes: 11 additions & 2 deletions index.html
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@
font: 200 1.1em "Helvetica Neue", Helvetica, Arial, sans-serif;
margin: 0;
}
h3:target {
h3:target, h3.target {
background: #F4ECFF;
margin: 1.9em -.2em -.1em -.2em;
padding: .1em .2em;
Expand Down Expand Up @@ -182,9 +182,18 @@
return c/2 * (-Math.pow(2, -10 * --t) + 2) + b;
};
$('#nav-community').click(function() {
if (history.pushState) {
history.pushState(null, null, '#community');

// ugh https://github.com/whatwg/html/issues/639
$('#community').addClass('target');
$(window).one('popstate', function() { $('#community').removeClass('target'); });
}
$('html, body').stop().animate({
scrollTop: $('#community').offset().top,
}, 600, 'easeInOutExpo', function() { location.hash = '#community'; });
}, 600, 'easeInOutExpo', function() {
if (!history.pushState) location.hash = '#community';
});
return false;
});
</script>
Expand Down

1 comment on commit 8d89f89

@laughinghan
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please sign in to comment.