Vue Scroll to top on pageload

2.7k Views Asked by At

I'm currently using Gridsome in my portfolio website. But when I'm on the bottom of a page on a mobile/tablet device that is longer then the page I'm navigating to, the page doesn't scroll to the top on Firefox. On Google Chrome it works fine.

I'm using the following code to scroll to the top of a page:

window.onbeforeunload = function () {
    window.scrollTo(0, 0);
}

I have tried other solutions, but nothing seems to work. I don't want to use any jquery for this solution.

2

There are 2 best solutions below

4
Rijosh On

Change your router configuration like follows,

const router = new VueRouter({
  routes: [...],
  scrollBehavior (to, from, savedPosition) {
    return { x: 0, y: 0 }
  }
})

This will scroll to top on every route changes.

If you're not using vue-router, then add the following code inside the mounted() hook of your component.

setTimeout(() => {
  document.body.scrollTop = document.documentElement.scrollTop = 0;
}, 500);
0
GlobalPlayer On

I have found the following workaround, it is not the best result but it works for me. Set the Y value to 1 or 2, Firefox seems to have a problem with the 0.

window.scrollTo(0, 2);