Skip to content

Commit

Permalink
Clicking TOC links changes hash fragment (#2019)
Browse files Browse the repository at this point in the history
* Fix smooth scroll breaking back button #1767
* Change URL's hash fragment when clicking on TOC
* Switch from hashchange to popstate event handler

This seems to have better behavior with the Forward button, on page load,
and always scrolls in the right direction.

Close #1767
  • Loading branch information
edemaine authored and mmistakes committed Jan 4, 2019
1 parent 2784b3a commit 33551c8
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 6 deletions.
23 changes: 21 additions & 2 deletions assets/js/_main.js
Original file line number Diff line number Diff line change
Expand Up @@ -61,8 +61,27 @@ $(document).ready(function() {
}, 400);
});

// init smooth scroll
$("a").smoothScroll({ offset: -20 });
// Smooth scrolling

// Bind popstate event listener to support back/forward buttons.
$(window).bind("popstate", function (event) {
$.smoothScroll({
scrollTarget: location.hash,
offset: -20
});
});
// Override clicking on links to smooth scroll
$('a[href*="#"]').bind("click", function (event) {
if (this.pathname === location.pathname && this.hash) {
event.preventDefault();
history.pushState(null, null, this.hash);
$(window).trigger("popstate");
}
});
// Smooth scroll on page load if there is a hash in the URL.
if (location.hash) {
$(window).trigger("popstate");
}

// add lightbox class to all image links
$(
Expand Down
Loading

0 comments on commit 33551c8

Please sign in to comment.