Skip to content

Commit

Permalink
Merge pull request #364 from nusjzx/310-autoscroll-after-page-loaded
Browse files Browse the repository at this point in the history
Autoscroll after the whole page is loaded

If the user navigates to 'index.html#some-heading', by default, the
browser will automatically scroll to the correct HTML header with
'some-heading' as its ID.

However, there is a race condition between the scrolling by the browser,
and the loading of components by Vue. Vue might take a long time to load
the components, so if the browser scrolls too early, then when the
components are fully loaded, the page appearance would have changed, and
the position is no longer accurate.

Let's force the browser to scroll again after Vue finishes loading,
by hooking Vue's 'mounted' lifecycle, and manually scrolling to the
anchor using jQuery inside the hook.
  • Loading branch information
yamgent authored Jul 24, 2018
2 parents aa6c0ea + 1d1edc0 commit 531a1bf
Showing 1 changed file with 12 additions and 0 deletions.
12 changes: 12 additions & 0 deletions asset/js/setup.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,12 @@

Vue.use(VueStrap);

function scrollToUrlAnchorHeading() {
if (window.location.hash) {
jQuery(window.location.hash)[0].scrollIntoView();
}
}

function setupSiteNav() {
// Add event listener for site-nav-btn to toggle itself and site navigation elements.
const siteNavBtn = document.getElementById('site-nav-btn');
Expand Down Expand Up @@ -29,6 +35,9 @@ function setup() {
// eslint-disable-next-line no-unused-vars
const vm = new Vue({
el: '#app',
mounted() {
scrollToUrlAnchorHeading();
},
});
setupSiteNav();
}
Expand All @@ -53,6 +62,9 @@ function setupWithSearch(siteData) {
window.location = `${page}${anchor}`;
},
},
mounted() {
scrollToUrlAnchorHeading();
},
});
setupSiteNav();
}
Expand Down

0 comments on commit 531a1bf

Please sign in to comment.