Jump to content
GreenSock

Search In
  • More options...
Find results that contain...
Find results in...
adamoc

GSAP 3 Scroll Trigger Issue With BarbaJS

Recommended Posts

Hi there, okay so thank you @ZachSaucier for your advice on what to do next with my situation. So I've made a little test , minimal and I think complete which shows the difference in the reaction of scrollTrigger with and without BarbaJS enabled on the page. So I have a homepage which has horizontal scroll perfectly available and working then I include a button to click the about page , click the button and brought to the about page (same animation but doesn't give you the same result) only able to scroll halfway across and not able to reach the footer. Wondering why this is the case and what can I do to combat the differences in the adjustment of the dimensions of the page made by Barba. 

Here's the site - https://testbarba.netlify.app/

Here's the code -

 

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="style.css">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.3.4/gsap.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.3.4/ScrollTrigger.min.js"></script>
    <script defer src="main.js"></script>
    <title>Document</title>
</head>
<body>
    <div class="container">
        <div class="page one">One</div>
        <div class="page two">Two</div>
        <div class="page three">Three</div>
    </div>
    <div class="about_btn_container">
        <a href="about.html">About</a>
    </div>
    <footer>
        All Rights Reserved &copy; Adamoc 2020
    </footer>
</body>
</html>

 

about.html

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="style.css">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.3.4/gsap.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.3.4/ScrollTrigger.min.js"></script>
    <script defer src="https://unpkg.com/@barba/core"></script>
    <script defer src="main.js"></script>
    <title>Document</title>
</head>
<body data-barba="wrapper">
    <div class="container" data-barba="container" data-barba-namespace="about">
        <div class="page one">One</div>
        <div class="page two">Two</div>
        <div class="page three">Three</div>
    </div>
    <div class="about_btn_container">
        <a href="about.html">About</a>
    </div>
    <footer>
        All Rights Reserved &copy; Adamoc 2020
    </footer>
</body>

</html>

main.js

const scrollAnimation = () => {
    let pages = [...document.querySelectorAll('.page')]
    gsap.to(pages, {
        xPercent: -100 * (pages.length - 1),
        ease: "none",
        scrollTrigger: {
            trigger: ".container",
            pin: true,
            markers: true,
            scrub: 1,
            snap: 1 / (pages.length - 1),
            // base vertical scrolling on how wide the container is so it feels more natural.
            end: () => "+=" + document.querySelector(".container").offsetWidth
        }
    });
}

scrollAnimation()
barba.init({
    sync: true,
    transitions: [{
        name: 'transition-base',
        async leave() {
            const done = this.async();
            await delay(1000);
            done();
        },
        async enter() {
            window.scrollTo(0, 0);
        },
    }],
    views: [
        {
            namespace: 'about',
            beforeEnter(data) {
            },
            afterEnter() {
                scrollAnimation();
            },
        }
    ],
});

Cheers Adam

See the Pen by (@) on CodePen

Link to comment
Share on other sites

Looking into this further I have happened upon the reason I think my situation above arises , but I have no clue how to fix it (is it a manual clearout job of the tags)??

So When on the home page I looked in the inspect element and saw that there's the elements for the tags(end marker , start marker , end scroller marker , start scroller marker and then pin spacer). Then went on the About page and observed that it seems the first elements don't get cleared out and new one's for the second page are added , thing is pin spacer element gets added with a different height altogether therefore you can only scroll halfway across the page like I observed above. So wondering how to go about solving my problem , any thoughts would be appreciated  🤙

I've attached the relevant screenshots of the inspect element below , note the page domain name in the grey bar at the top to see which screenshot belongs to which page. 

Cheers Adam 

Screenshot 2020-06-29 at 13.32.52.png

Screenshot 2020-06-29 at 13.34.00.png

Link to comment
Share on other sites

Hey Adam. This is 100% a Barba.js question, not at all related to GSAP. So don't expect to get this level of help next time if you're asking about Barba.js issues :) But this time I'm happy to help.

 

The code that you provided is close to a minimal and complete demo. But there are a few things that I had to do to get it working:

  • Load Barba.js.
  • Find the styles file that is on your live version (you didn't provide it in the post above).
  • You don't have the data attributes that Barba uses in the index.html page. So I had to add those.
  • In general you should include your script tags in the bottom of your document right before the closing </body> tag.
  • Once I got all of that working, it throws an error saying delay is not defined. So I had to define a delay function that returns a promise that resolves after the given number of milliseconds.

Additionally the live version that you have errors out as well (check the console to see). When creating demos, please make sure that we will have everything that we need to recreate the issue with as little effort as possible (you're much more likely to get more and faster responses that way :)).

 

Now, onto the actual issue here:

The main issue is that enter() runs before the page is fully loaded. To fix it, I recommend using a setTimeout (or requestAnimationFrame) to delay the scrollAnimation function call a little bit. Here's what works for me:

 

Index:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="style.css">

    <title>Document</title>
</head>
<body data-barba="wrapper">
    <div data-barba="container" data-barba-namespace="index">
        <div class="container">
            <div class="page one">One</div>
            <div class="page two">Two</div>
            <div class="page three">Three</div>
        </div>
        <div class="about_btn_container">
            <a href="about.html">About</a>
        </div>
    </div>
    <footer>
        All Rights Reserved &copy; Adamoc 2020
    </footer>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/@barba/core@2.9.7/dist/barba.umd.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.3.4/gsap.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.3.4/ScrollTrigger.min.js"></script>
    <script defer src="main.js"></script>
</body>
</html>

About:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="style.css">
    
    <title>Document</title>
</head>
<body data-barba="wrapper">
    <div data-barba="container" data-barba-namespace="index">
        <div class="container">
            <div class="page one">One</div>
            <div class="page two">Two</div>
            <div class="page three">Three</div>
        </div>
        <div class="about_btn_container">
            <a href="index.html">Index</a>
        </div>
    </div>
    <footer>
        All Rights Reserved &copy; Adamoc 2020
    </footer>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.3.4/gsap.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.3.4/ScrollTrigger.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/@barba/core@2.9.7/dist/barba.umd.min.js"></script>
    <script defer src="main.js"></script>
</body>
</html>

Main.js:

let myAnim;
const scrollAnimation = () => {
  const pages = [...document.querySelectorAll('.page')];
  const container = document.querySelector(".container");

  myAnim = gsap.to(pages, {
      xPercent: -100 * (pages.length - 1),
      ease: "none",
      scrollTrigger: {
          trigger: container,
          pin: true,
          scrub: 1,
          snap: 1 / (pages.length - 1),
          // base vertical scrolling on how wide the container is so it feels more natural.
          end: () => "+=" + container.offsetWidth
      }
  });
}

function delay(ms) {
  return new Promise(resolve => setTimeout(resolve, ms));
}

if(typeof myAnim === "undefined") {
  scrollAnimation();
}

barba.init({
  sync: true,
  transitions: [{
      name: 'transition-base',
      async leave() {
          const done = this.async();
          await delay(1000);
          done();
      },
      async enter() {
          document.documentElement.scrollTop = 0;
          setTimeout(scrollAnimation, 10);
      },
  }],
});

 

Link to comment
Share on other sites

Right @ZachSaucier , I know you're sick of seeing my name pop up talking about GSAP and Barba Combination. The problem is BarbaJs doesn't really have a forum (well from what I could find anyway), but what I will confess to and start trying to do is debug my problems more before coming to this forum that's why yesterday I basically spent the day trying to debug my actual first problem I still can't get. I turned off all functions bar one and stepped through all variable values at all stages of DOM loading and manipulation through the Barba hooks , I identified the places I needed to add a setTimeout and also I found out which hooks come first(enter , DOM load , etc... ) and that the afterEnter hook is probably the best place to initialize anything you want because if you place a function call in there it gets called whether or not you're transitioning through Barba. As I said before I really did try to debug this time as much as possible and identified my problem I think . As I said in a earlier post , markers are added every time by GSAP on page load (which I'm guessing is how ye make the pinning possible starting at the start marker pin until the end marker and then the other two are to do with the scroll position on the page. So what I observed in the inspect element is that when you transition to a page with Barba the amount of markers doubles and so pushes down the start marker and end marker down the page causing my animation to start at a different place which is what I'm observing is happening in my site now if i go to homepage and click about , to counteract this what I have done is got rid of all the markers on page load so that GSAP can add it's new markers and not be pushed down , however I don't know how but the markers added are still getting pushed down even though they're only ones there now , what's happening is lets take this problem for example,

 

On Normal page Load my 

Start Marker top - 2371px

Height Of my Container that pins - 4320px 

End Marker top - 6691px 

- This works without a hitch perfectly

 

After Barba Transition Page Load 

Start Marker top - 7175px

Height Of my Container that pins - 4320px 

End Marker top - 11495px 

- This works at the wrong position therefore doesn't perform properly (overlapping other elements and what not) 

 

So to be clear If i didn't remove some of the markers page would look like this like it does now 

2371

+4320

6691

7175

+4320

11495

 

Now when I clear it takes care of the first one's so you're left with this now 

7175

+4320

11495

 

Now What I want is to move these positions to the same as page load normal that being 

2371

+4320

6691

 

But when I tried to do this the actual top value changed / updated as the tag jumped up but seems GSAP somewhere has it defined that the animation is still getting set at the marker at 7175 so when I scroll to that position this is when it actually works but at the wrong position as already stated , further down the page . Wondering how are those markers position set and/or the way you use to identify where to start animation and how would I go about changing these positions to my desired ones on page load after barba transition. 

 

So now to your post above Zach , I intentially left out Barba Script and Barba wrapper data properties on the homepage as you said you wanted a simple but effective test case so you could see what I was on about that animation with Barba and without is different so I set Homepage as page without the Barba and the about page as page with it, as for not including all the resources you needed to carry out the experiment yourself stupidly I thought you were going to just look at my code , at the live version and work it out from there , I didn't think you were going to reverse engineer it so sorry for that in the future I will most definitely be more thorough with providing all resources if i'm asking a question on this forum. I'm sorry , this is all pretty new to me writing in forums as I haven't wrote questions before on forums as I'm normally a hard worker 100% never give up until you got it don't show someone else they are better than you guy and you'll get this . But taking a step backward from this over this year I have identified that asking for help is not a form of weakness but strength as you it's through help you get better and learn more things , otherwise you stuck in a rut for a long time leading to unfinished projects. So I have taken the leap to ask for more help I do agree however I should have debugged this issue above a bit better but I'm trying that's all I can do 🤷‍♂️. Okay what I will say and acknowledge is a huge thank you to you and the team at GSAP who work tirelessly to help us create spectacular animations and ScrollTrigger is another amazing addition to this outstanding library. Personally thank you for sorting the stupid bug I missed yesterday 🤙 

 

Cheers Adam 

 

 

 

 

Link to comment
Share on other sites

If markers are causing issues just don't use markers :) As far as I understand, if you call ScrollTrigger.refresh() after whatever event is changing things around it should work fine.

 

Asking for help is not an issue at all - we just can't provide support for issues that are unrelated to GSAP most of the time. We do our best to help and point people in the right direction but we don't have the capacity to do that for every question and issue. 

  • Like 1
Link to comment
Share on other sites

Decided I should leave this here and contribute for once lol 😃.

Update : For anyone who might be coming to this in the future ,

I observed that when I resized the window the markers updated their position idk why but this is absolutely unreal because what I did was basically simulate a window resize to get the markers back to their desired locations 

So for anyone who comes to this and observes your scroll markers are in a different position after a Barba page transition , this is what I did 

I have my afterEnter hook calling a function called aboutInit to handle all page onboarding issues I'm facing, in the function what it does first is what I mentioned above checks all the classes in the DOM for gsap one's against a regex and then finds these gsap markers and removes them so now you're only left with no markers . Then I call my actual function to do the horizontal scroll effect and give me a brand new set of markers and now you're left with that set of markers in the wrong positions (as stated above - read that before continuing ). So then just simulate a window resize event to kick the markers back into their original positions then everything is in order and your animation should start and end in the right place . What I did was check the top position on just reload of the page in the right original position , then do a barba transition let all this happen above and bam left with the same top positions for the markers. Hope that makes sense . 🤙

 

Here is the code - 

 

aboutInit

// About Page Functions 
const aboutInit = () => {
    let horizontalscrollAnim,
    cleanGSAP()
    if(typeof horizontalscrollAnim === "undefined") {
        scroll_facts_tl_func();
    }
    window.dispatchEvent(new Event('resize'));
}

const cleanGSAP = () => {
    const allClasses = [...document.querySelectorAll('[class]')]
    let gsapArray = []
    if(allClasses.length <= 134) return
    for (var i = 0; i < allClasses.length; i++) {
        if (/gsap-/.test(allClasses[i].className)) {
            gsapArray.push(allClasses[i].className);
        } else 
            break
    }
    gsapArray.map(tag => document.querySelector(`.${tag}`).remove())
}

//You don't need this but it's just so you know what I'm calling 

const scroll_facts_tl_func = () => {
    const facts = [...document.querySelectorAll('.fact')],
    factsContainer = document.querySelector('.factsContainer');
    let xPercent
    window.matchMedia("(max-width: 600px)").matches ? xPercent = -85 : xPercent = -115
    horizontalscrollAnim = gsap.to(facts, {
        xPercent: xPercent * (facts.length - 1),
        ease: "none",
        scrollTrigger: {
            trigger: ".factsContainer",
            pin: true,
            pinSpacing: true,
            // markers: true,
            scrub: 1,
            snap: 1 / (facts.length - 1),
            start: "top top",
            // base vertical scrolling on how wide the container is so it feels more natural.
            end:  `+=${factsContainer.offsetWidth}` //4320
        }
    });
}

 

Helper Methods 

// Helper Functions
const delay = (ms) => {
    return new Promise(resolve => setTimeout(resolve, ms));
}

 

Barba Initialization 

barba.init({
    sync: true,
    transitions: [{
        name: 'transition-base',
        async leave() {
            const done = this.async();
            pageTransition();
            await delay(1000);
            done();
        },
        async enter() {
            window.scrollTo(0, 0);
        },
    }],
    views: [
        {
            namespace: 'about',
            afterEnter() {
                aboutInit()
            }
        }
    ],
});

Here's also a Test Site I put to show what I mean just do exactly as stated to see the effect and discreptancy in the markers positions due to Barba transition

 

1. Go to https://testbarba.netlify.app/

2. Click the about page - this will trigger barba transition - take note of the markers positions(end and start in the inspect element) 

3. Then just reload the about page and you will notice the different positions of your markers upon load (again in the inspect element) 

4. You can use above to fix this , if this is your problem 

 

Cheers Adam 

Link to comment
Share on other sites

Hi  @ZachSaucier ,  nope I'm not using the markers but the markers are indicating from what i gather anyway where the animation starts so getting them in the right position is key and then turn them off . So I was just using them as a guide really , oh hahahah I found a workaround so but I'll try that either if I run into this very problem again hahaha . No I completely understand the honus is not on you as that is not your problem really , if i ever run into Barba problem again , do you have any forums I could use ? Thanks a million for your help over last few days , think I'll just about be able to launch it in large part thanks to you . Youre a sound man , see ya again i imagine lol 👌😂

Cheers Adam 

  • Like 1
Link to comment
Share on other sites

5 minutes ago, adamoc said:

if i ever run into Barba problem again , do you have any forums I could use ?

We don't, Baba isn't a GreenSock product.

Link to comment
Share on other sites

 

2 minutes ago, ZachSaucier said:

We don't, Baba isn't a GreenSock product

No I know that , but do you know of any I meant like because I couldn't find any anywhere when I searched.

Link to comment
Share on other sites

  • 11 months later...

For any future readers, I ran into a very similar problem as Adam and was able to solve it with ScrollTrigger’s getAll() and kill() functions.  Added to Barba’s afterEnter hook.

 

My ‘cleanGSAP’ function looked like this:
 

const cleanGSAP = () => {
	let existingScrollTriggers = ScrollTrigger.getAll();
	for (let index = 0; index < existingScrollTriggers.length; index++) {
		const singleTrigger = existingScrollTriggers[index];
		singleTrigger.kill(false);
	}
	ScrollTrigger.refresh();
	window.dispatchEvent(new Event("resize"));
};

 

  • Like 2
Link to comment
Share on other sites

Thanks, @austenhart! A slightly more concise version: 

const cleanGSAP = () => {
	ScrollTrigger.getAll().forEach(t => t.kill(false));
	ScrollTrigger.refresh();
	window.dispatchEvent(new Event("resize"));
};

👍

  • Like 2
  • Thanks 1
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
  • Recently Browsing   0 members

    • No registered users viewing this page.
×