javascriptjquerycssscrollbarbajs

How to scroll new page to top on load on click?


I'm using barba.js to fade new pages in. Code must be placed between the barba wrapper div. When I click a link to a new page though, the new page fades in at the same position as the previous page was in. So if the user clicks a link, the new page is loading in near , which I don't want.

How can I get the new page to load in at the top?

I found the answer on stack about scrollRestoration function but I still don't understand how to make this work.

Could somebody help me to compile the js code below, add some css or html to fix this issue?

$(window).scrollTop(0);
if ('scrollRestoration' in history) {
    history.scrollRestoration = 'manual';
}
function delay(n) {
  n = n || 2000;
  return new Promise((done) => {
    setTimeout(() => {
      done();
    }, n);
  });
}

function pageTransition() {
  var tl = gsap.timeline();

tl.to(".animate-this", {
     duration: .2,  opacity: 0, delay: 0,  y: 30,  //scale:0, delay: 0.2, 
  });
  tl.to(".animate-this", {
     duration: 0,  opacity: 0, delay: 0,  scale:0,  //scale:0, delay: 0.2, 
  });

  tl.fromTo(".loading-screen", {width: 0, left: 0}, {
    duration: 1,
    width: "100%",
    left: "0%",
    ease: "expo.inOut",
    delay: 0.3,
  });

  tl.to("#svg-1", {
    duration: 1,  opacity: 0,  y: 30, stagger: 0.4, delay: 0.2, 
  });

  tl.to(".loading-screen", {
    duration: 1,
    width: "100%",
    left: "100%",
    ease: "expo.inOut",
    delay: 0, //CHANGE TIME HERE END TRANS
  });




  tl.set(".loading-screen", { left: "-100%", });
  tl.set("#svg-1", { opacity: 1,  y: 0 });
}



function contentAnimation() {
  var tl = gsap.timeline();
  tl.from(".animate-this",  { duration: .5, y: 30, opacity: 0, stagger: 0.4, delay: 0.2 });
}

$(function () {
  barba.init({
    sync: true,

    transitions: [
      {
        async leave(data) {
          const done = this.async();

          pageTransition();
          await delay(2500);
          done();
        },

        async enter(data) {
          contentAnimation();
        },

        async once(data) {
          contentAnimation();
        },
      },
    ],
  });
});

Have a look: https://pasteboard.co/Ja33erZ.gif

Here also a codepen to check my issue (html,css): https://codepen.io/cat999/project/editor/AEeEdg


Solution

  • scrollRestoration shouldn't be necessary, this can be done by resetting scroll position during the transition:

      tl.fromTo(".loading-screen", {width: 0, left: 0}, {
        duration: 1,
        width: "100%",
        left: "0%",
        ease: "expo.inOut",
        delay: 0.3,
        onComplete: function() {
          window.scrollTo(0, 0);
        }
      });
    

    Working example here: https://codepen.io/durchanek/project/editor/ZWOyjE