Barba: Manage previous scroll position with back/forward browser buttons

Created on 19 Jul 2019  路  6Comments  路  Source: barbajs/barba

Most helpful comment

For the moment, I've added a scroll property to the history items.
With trigger back|forward, you can use scroll.x|y from barba.history.current|previous.

All 6 comments

Hi,

In my current project, I disable the scroll restoration after the Barba init stage, like this:

if ('scrollRestoration' in history) {
  history.scrollRestoration = 'manual';
}

Then in the enter hook, just after removing the current container, I scroll the window to the top to properly display the next page:

current.container.remove();
window.scrollTo(0, 0);

It could be very useful to have a property to manage this behavior inside Barba. :wink:

For the moment, I've added a scroll property to the history items.
With trigger back|forward, you can use scroll.x|y from barba.history.current|previous.

Perfect fix!
If we have new issues regarding back/forward browser buttons, we will refer to this thread. :v:

@thierrymichel I'm having trouble wrapping my head around this. Could you post an example on how we can restore the scroll position on the browser back button? while history.scrollRestoration = 'manual'; is in place?

So far I got

barba.hooks.before(() => {
   window.scrollTo(barba.history.current.scroll.x, barba.history.current.scroll.y);
});

would appreciate an example of how you handle that, I managed to solved that with the following code, but I'm sure there is better way:

if ('scrollRestoration' in history) {
  history.scrollRestoration = 'manual';
}
let linkClicked = false;
let scrollY = false;

barba.hooks.beforeEnter(() => {
  if (linkClicked) {
    // Scroll top of page
    window.scroll(0, 0);
  }
  else if (scrollY) {
   // Scroll back to Y position
    window.scroll(0, scrollY);
    scrollY = false;
  }
  else {
    window.scroll(0, 0);
  }
});

barba.hooks.afterLeave((data) => {
// Register data trigger
  if (data.trigger === 'back') {
    linkClicked = false;
  } else {
    linkClicked = true;
  }
})
barba.hooks.beforeLeave(() => {
  // Register last scroll Y position
  if (!scrollY) {
    scrollY = barba.history.current.scroll.y
  }
})

After doing a little more investigation, I found this way to be the best

history.scrollRestoration = "manual";`

var scrollPosY = 0

barba.hooks.enter((data) => {
  if(data.trigger !== "back") {
    scrollPosY = barba.history.current.scroll.y;
  }
});

barba.hooks.after((data) => {
  if(data.trigger !== "back") {
    window.scrollTo(0,0);
  } else {
    window.scrollTo(0, scrollPosY)
  }
});

EDIT: found a better solution

Was this page helpful?
0 / 5 - 0 ratings

Related issues

kram08980 picture kram08980  路  3Comments

ershad989 picture ershad989  路  4Comments

S1SYPHOS picture S1SYPHOS  路  3Comments

gitgudcameron picture gitgudcameron  路  3Comments

luglio7 picture luglio7  路  4Comments