Jump to content
GreenSock

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

Reset timeline after barba.js page transition

Recommended Posts

@akapowl thanks for the feedback, that makes sense!

@ZachSaucier thanks for the help again!

 

Time to dig deeper in both Barba and GSAP now.

Link to comment
Share on other sites

  • 4 months later...

Hi there , I have read this thread as I have come back into this problem too . My problem is before transitioning the timeline loads perfectly and executes as i want however after transitioning to another page and then clicking back to the home screen the timeline doesn't play half the tweens specifically the part animating my logo. I believe after reading the thread it might come down to the fact as @mdelp has implied that elements targeted with a timeline inside the barba container are removed or replaced but I have no clue how to go about fixing this problem as i need all this content withing barba container. 

On 2/14/2020 at 4:38 PM, akapowl said:

@mdelp

One thing I can tell you is, that the reason, why you do not need to reinit your scripts in this setup, is beacause the only script that you use (except for the barba setup)  is applied to the navigation module, which is outside of the <main data-barba="container"> . This means that it does not get removed and reapplied on every transition, but stays where it is and thus does not need to be re-initiated.

You will only need to re-initiate scripts that aim at elements, that are inside of  the <main data-barba="container"> and thus get removed and/or replaced.

Here's a link to my website where you will find the problem occuring if you follow the steps outlined above -> Move to different page and then back to homepage again - https://adamoceallaigh.netlify.app/

Cheers,

Adam

Link to comment
Share on other sites

16 minutes ago, adamoc said:

I believe after reading the thread it might come down to the fact as @mdelp has implied that elements targeted with a timeline inside the barba container are removed or replaced but I have no clue how to go about fixing this problem as i need all this content withing barba container. 

You should probably recreate the animation when a new page has been loaded.

Link to comment
Share on other sites

Hi adamoc,

 

I was able to get everything working by making sure that all my functions that are located inside the barba-container (i.e. the content container that gets replaced) get reloaded everytime a barba transition ends.

 

So basically, let's say you have a function:

 

function function_name() {
	// Function
}

You have to reinit that function everytime a page transition ends, using a Barba hook:

 

barba.hooks.afterEnter(function() {
  function_name();
});

More info on the Barba hooks: https://barba.js.org/docs/advanced/hooks/

 

Functions that are inside the wrapper, but not the container (so the functions that do not get replaced every page transition) do not have to be releoded.

  • Like 1
Link to comment
Share on other sites

Hey @adamoc.

 

Seems like you are having issues similar to what mine were about.

This here is probably what is most important to get your head around with barba:

 

On 2/13/2020 at 7:17 PM, OSUblake said:

 

... looks like you are trying to replay the scrollIndicationAnimation timeline. That obviously won't work because the original elements aren't inside the page anymore. You would have to create a new timeline to target the new elements. 

 

Everything inside the barba container will get removed on transitioning to another page and will be replaced with the content inside the barba-container of the page you are aiming at. When you revisit the initial page then, the content is loaded fresh. Every timeline you might initiate on load of window e.g., will be aiming at those elements that are there on load and will stay 'connected' to these even when they are removed on transition. But since they actually are not there anymore - but have been replaced -  when you come back to this page, you won't see anything happen.

 

You will have to find a way to reinitiate the timeline for page-specific elements everytime you transition to that page, just like @mdelp suggested above. Hope this helps clear things up a bit. There is a lot to consider when using something like barba.

  • Like 1
Link to comment
Share on other sites

Thank you so much for your  quick and informative replies .

 

Okay I get what you are saying @mdelp and @akapowl and have updated my JS code to use a function to restart the timeline upon call in the hook all at once but it doesn't seem to be working and I can't tell why , it appears the individual tweens ( gsap.to) is working as the heading is being pushed in upon homepage revisit after navigating with barba , and this is enabled by using a seperate tweens and not a timeline , so is it a problem with the timeline ??. 

 

But then I have tried to use a hamburger button in the phone version it pops up and i tried to click it and i'm able in the first instance but seems that script stops working upon return after barba navigation .

 

I've tried putting the code back into the hook (beforeAfter as indicated above) and to no avail , and as indicated above I think if i put another script in to tod something subsequent to the gsap it probably wouldn't work either so how do i get around this issue or fix my existing code to basically refresh all the scripts, like the function window.load or $(document).ready(()=>{}) would do ??

 

//Variable Declarations and Function Definitions 

let viewBox = "",
    heading_Pos = [0, 0],
    displayState = ""
    hamburger_display_button = Array.from($('.mobile_nav_sticky'))[0]
    opened_nav_buttons = document.querySelector('.options')
    logo = $(".Actual_Logo_Svg");
    // Morphing Circles and ellipses to paths to be able to morph them and checking the viewbox for device size
    MorphSVGPlugin.convertToPath("ellipse");
    shapes = Array.from($('.Logo_In_Shapes path'))
    
const logo_tl_func = () => {
    let logo_tl = gsap.timeline({
        onComplete: moveLogo,
    })
    // Morphing into the Logo
    logo_tl.staggerFrom(shapes, 1, {
        y: -600,
        autoAlpha: 0,
        ease: "bounce"
    }, 0.15)
    logo_tl.staggerTo(shapes, 1, {
        fill: '#F0C368',
    }, 0.05)
    let firstAnimation = gsap.to('.shapes', {
        duration: 2,
        morphSVG: ".Logo_Proper_Background"
    });
    let secondAnimation = gsap.to('.textShape', {
        duration: 2,
        fill: '#1D373F',
        morphSVG: ".Logo_Proper_Text"
    });
    logo_tl.add([firstAnimation, secondAnimation])
    console.log('Well you should have animated rn')
}

const changeViewBox = media_query => {
    media_query.matches ? viewBox = "-150 -180 2495 890" : viewBox = "-150 -350 3574 880"
    media_query.matches ? heading_Pos = [-511, -15] : heading_Pos = [-1540, 40];
    media_query.matches ? displayState = "none" : displayState = "block"
}

const moveLogo = () => {
    gsap.to(logo, {
        attr: { viewBox: viewBox },
        duration: 3
    })
    fadeInHeadingAndLinks()
}

const fadeInHeadingAndLinks = () => {
    gsap.to('.nav_links', {
        display: displayState,
        scale: 1,
        duration: 3
    })
    gsap.fromTo('.logo_heading', {
        x: 1340,
        y: 20
    }, {
        display: "block",
        x: heading_Pos[0],
        y: heading_Pos[1],
        // scale:1,
        duration: 3
    })
    gsap.to('.mobile_nav_sticky', {
        display: "block",
        scale: 1,
        duration: 5
    }, "+=.7")
}

const pageTransition = () => {
    var tl = gsap.timeline();
    tl.to('.loading_container', {
        duration: 1.2,
        width: "100%",
        left: "0%",
        ease: "Expo.easeInOut",
    })
    .to('.loading_container', {
        background: "#f0c368"
    })
    .to('.loading_container', {
        duration: 1.2,
        width: "0%",
        right: "0%",
        ease: "Expo.easeInOut",
    })
}

// Helper Functions

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


// Initialization Methods
$(document).ready(() => {
    window.matchMedia("(max-width: 600px)").matches ? logo.attr('viewBox', '-350 -700 1274 1680') : logo.attr('viewBox', '-680 -380 2074 1080')
    var viewbox = window.matchMedia("(max-width: 600px)")
    changeViewBox(viewbox)
})

hamburger_display_button.onclick = () => {
    opened_nav_buttons.classList.toggle('open')
};

barba.init({
    sync: true,
    transitions: [{
        async leave(data) {
            const done = this.async();
            pageTransition();
            await delay(1000);
            done();
        },
        async enter(data) {
            window.scrollTo(0, 0);
        },
    }]
});

// barba.hooks.enter(() => {
    
// });
barba.hooks.afterEnter(() => {
    logo_tl_func()
    hamburger_display_button.onclick = () => {
        opened_nav_buttons.classList.toggle('open')
    };
});

https://adamoceallaigh.netlify.app/

Cheers , 

Adam 

Link to comment
Share on other sites

Just thought of something there, as it's basically not a new DOM and the elements have been replaced and/ or removed , the variable declarations at the start become abundant no?? So if i was to put a function to redeclare these variables and basically allow DOM to refind these elements and call it in the hook then it might work ??

Adam

Link to comment
Share on other sites

3 minutes ago, adamoc said:

so is it a problem with the timeline ??

Very unlikely that's it's an issue with timelines.

 

Just now, adamoc said:

if i was to put a function to redeclare these variables and basically allow DOM to refind these elements and call it in the hook then it might work ??

If an element is switched out then you need to update any variable references, yes :) 

 

FYI you don't need staggerFrom any more. Just use a regular .from() tween with a stagger property: https://greensock.com/docs/v3/Staggers

 

Your eases are also invalid. Use the condensed string form instead:

 

Link to comment
Share on other sites

Like this:

let viewBox = "",
    heading_Pos = [0, 0],
    displayState = ""
    hamburger_display_button = Array.from($('.mobile_nav_sticky'))[0]
    opened_nav_buttons = document.querySelector('.options')
    logo = $(".Actual_Logo_Svg");
    // Morphing Circles and ellipses to paths to be able to morph them and checking the viewbox for device size
    MorphSVGPlugin.convertToPath("ellipse");
    shapes = Array.from($('.Logo_In_Shapes path'))

const init = () => {
    viewBox = "",
    heading_Pos = [0, 0],
    displayState = ""
    hamburger_display_button = Array.from($('.mobile_nav_sticky'))[0]
    opened_nav_buttons = document.querySelector('.options')
    logo = $(".Actual_Logo_Svg");
    // Morphing Circles and ellipses to paths to be able to morph them and checking the viewbox for device size
    MorphSVGPlugin.convertToPath("ellipse");
    shapes = Array.from($('.Logo_In_Shapes path'))
}

barba.hooks.afterEnter(() => {
    logo_tl_func()
    init()
    hamburger_display_button.onclick = () => {
        opened_nav_buttons.classList.toggle('open')
    };
});

??

Link to comment
Share on other sites

Whoop whoop , after a little bit of tweaking and yere help she's working perfectly.  :)

 

Thanks a million lads ( @ZachSaucier @akapowl @mdelp) . 

 

I do have a question though as this hook runs after each transition say if I wanted to start a timeline on the projects page - using anotherJS file.

 

First of all , would I have to initialize Barba again in this file considering i'm using it already to get onto this page ??

 

Secondly the fact that these elements aren't on the homepage, so when I then initilize and create references to them on the second JS file if i transition to another page and back to this page how do I reference them in this page without barba or the hook.

 

I just think that if i do it on the homepage.js it would all get very cluttered and this page wouldn't have access to the objects on the other page (or maybe it would as it's just swapped in so now the DOM does have access to it ) I really don't know.

 

I'm just looking for clarity as to how to expand my program i guess , and when i do so,  do i keep needing to rereferencing objects and functions in that same hook on that JS file or can i spread it out to other JS files ?? 

 

Cheers Adam

 

Finished Product - https://adamoceallaigh.netlify.app/

Link to comment
Share on other sites

1 minute ago, adamoc said:

First of all , would I have to initialize Barba again in this file considering i'm using it already to get onto this page ??

You only need to initialize Barba on the page load (no matter what the first page is). After that it should be loaded.

 

4 minutes ago, adamoc said:

Secondly the fact that these elements aren't on the homepage, so when I then initilize and create references to them on the second JS file if i transition to another page and back to this page how do I reference them in this page without barba or the hook.

I'm not following.

 

I think you should try to look up some resources on how to structure things with barba.js. I think looking at how other people do it could be helpful. It's not really related to GSAP.

Link to comment
Share on other sites

Thanks @ZachSaucier  

 

11 minutes ago, ZachSaucier said:

I think you should try to look up some resources on how to structure things with barba.js. I think looking at how other people do it could be helpful. It's not really related to GSAP.

That's fair , just thought since you might know but yeah i'll definitely look into it.

Cheers ,

Adam

Link to comment
Share on other sites

@adamoc

Unfortunately working with barba most certainly results in a pretty complex bit of code, that isn't that easy for me to get my head around, if I didn't write it myself. But what you can do in barba is the following just as an example.


You can give your index.html the barba-namespace 'index' and your about.html the barba-namespace 'about', which you set up in your html-files like so. In your index.html it could be like this:

 

<main data-barba="container" data-barba-namespace="index">

 

This will come in very handy for triggering different functions on transition to different pages.

 

When you initialize barba you can then access these namespaces in VIEWS like so:

 

barba.init({
// Some options here
transitions: [            
                {
                    name: 'default',
                    // Available hooks like…
                    beforeOnce( current, next, trigger ) {
                    ...
                    },
                    // More hooks regarding this transition here...
                },

            // More transitions here....
          ],
 
views: [
 
    {
        // Actions taken ONLY when certain page is viewed.
        namespace: 'index',
 
        // Available hooks…
 
        afterEnter(data) {      
 
            playYourAnimationForTheHomepage();  
 
        },
 
        // More hooks regarding this namespace only...
 
    },
 
    // More namespaces, like maybe 'about' for your about.html ...
 
    ],
 
...

 

In that views-section you can run functions that will only be triggered on a certain hook for when a certain namespace/page is being viewed.

If I understood correctly, this might be the right path to a solution for your problems.

 

Read more about views here.
https://barba.js.org/docs/advanced/views/

 

But beware - I think the hooks for views differ from the global hooks that are available in barba and the hooks for transitions.

  • Like 1
Link to comment
Share on other sites

@adamoc

 

I'll just dump my Barba code here, maybe it can be of use to anyone. Please note that I'm not using ES6 syntax, so I've used slightly other syntax than the Barba docs.

 

function barbaInit() {

	barba.hooks.afterLeave(function() {
		$('.c-slider__slides').slick('unslick');
		$('.c-slider-large__slides').slick('unslick');
		$('.c-slider-multiple__slides').slick('unslick');
	});

	barba.hooks.beforeEnter(function() {
		lazyloadInstance.update();
	});

	barba.hooks.afterEnter(function() {
		scrollItems();
		smoothScroll();
		rotator();
		sliderProjects();
		sliderLarge();
		sliderMultiple();
	});

	barba.hooks.after(function() {
		ga('set', 'page', window.location.pathname);
		ga('send', 'pageview');
	});

	barba.init({
		transitions: [{
			name: 'transition-base',
			preventRunning: true,
			timeout: 5000,	// default: 2000

			leave: function() {
				var done = this.async();
				if( $('.c-hamburger').hasClass('is-active') ) {
					$('.r-header, .hamburger, .c-hamburger').removeClass('is-active');
					gsap.to('.overlay', {left: 0, duration: 0.75, ease: 'cubicbezier', onComplete: done});
				} else {
					gsap.to('.overlay', {left: 0, duration: 0.75, ease: 'cubicbezier', onComplete: done});
				}
			},

			enter: function(data) {
				var done = this.async();

				// Rewind the navigation overlay to start
				tl_nav_master.pause(0);

				// Scroll out the transition overlay
				gsap.to('.overlay', {left: '100%', duration: 0.75, delay: 0.25, ease: 'cubicbezier', clearProps: 'all'});

				// Scroll the viewport back to the top before page transition
				$(window).scrollTop(0);

				done();
			},
		}],
		
		views: [{
			namespace: 'home',
			afterEnter() {
				anim_home_in();
			},
		},
		{
			namespace: 'project',
			afterEnter() {
				anim_project_in();
			},
		},
		{
			namespace: 'about',
			afterEnter() {
				anim_about_in();
			},
		},
		{
			namespace: 'services',
			afterEnter() {
				anim_services_in();
			},
		},
		{
			namespace: 'service',
			afterEnter() {
				anim_service_in();
			},
		}],
	});

}

The global hooks at the top are hooks that need to fire every page transition.
Then I have a base transition between all pages.

And finally I have views that contain the animation that specifically need to run when a page enters the namespace with data-barba-namespace="home".

  • Like 3
Link to comment
Share on other sites

Omg thanks for this @akapowl and @mdelp , this is exactly what I was looking for . Thanks so much didn't see these responses until now. 

Now unfortunately I have a new problem and it's either with Barba or Gsap ScrollTrigger itself I have no clue . So in my website , when I go from the homepage to the about page everything works as normal except the horizontal scroll part that I have put in (Facts Section) , thing is I do this very same action on mobile and it works perfectly sometimes and then other times it does the same as it does with the Desktop Version , so it's either my code and the way I have implemented the horizontal scroll but thing is when I go directly to the page as in not through the homepage and just initiate all the functions in about.js independently , everything including the horizontal scroll works as desired and perfectly , so I don't know which is causing the problem , could ye have a look maybe ?? 

 

Also I just have a few questions about your code above @mdelp , You define the function barbaInit() but where is this called and when ?? , also are those anim_about_in() and other view specific functions your initializers for the page or just animating the page in?? . Just want to clarify aswell , like i mentioned above if someone clicks a link that loads the about page again or something or goes directly to the about page the Barba animations are gone so therefore if you're reliant on Barba to initialize your scripts upon that specific page load then your scripts are not going to be initialized so do you call them independently like above in their seperate JS files too?? Last thing I want to clarify if i have a seperate stylesheet for each page , do I even need to include it in the seperate pages( about etc) as they will be redundant if barba is just gonna use my homepage as the one page for my application so would I be better off loading in all my stylesheets for all my seperate pages on the homepage or just put them to load in dynamically once the view with namespace ?? occurs??.

 

 

So here is my homepage.js (Barba Init code) 

//Variable Declarations and Function Definitions 
let viewBox = ""
heading_Pos = [0, 0]
displayState = ""
hamburger_display_button = Array.from($('.mobile_nav_sticky'))[0]
opened_nav_buttons = document.querySelector('.options')
logo = $(".Actual_Logo_Svg")
// Morphing Circles and ellipses to paths to be able to morph them and checking the viewbox for device size
MorphSVGPlugin.convertToPath("ellipse");
shapes = Array.from($('.Logo_In_Shapes path'))

const homeInit = () => {
    viewBox = "",
        heading_Pos = [0, 0],
        displayState = ""
    hamburger_display_button = Array.from($('.mobile_nav_sticky'))[0]
    opened_nav_buttons = document.querySelector('.options')
    logo = $(".Actual_Logo_Svg");
    // Morphing Circles and ellipses to paths to be able to morph them and checking the viewbox for device size
    MorphSVGPlugin.convertToPath("ellipse");
    shapes = Array.from($('.Logo_In_Shapes path'))
}

const logo_tl_func = () => {
    let logo_tl = gsap.timeline({
        onComplete: moveLogo,
    })
    // Morphing into the Logo
    logo_tl.from(shapes, 1, {
        y: -600,
        autoAlpha: 0,
        ease: "bounce",
        stagger: 0.15
    })
    logo_tl.to(shapes, 1, {
        fill: '#F0C368',
        stagger: 0.05
    })
    let firstAnimation = gsap.to('.shapes', {
        duration: 2,
        morphSVG: ".Logo_Proper_Background"
    });
    let secondAnimation = gsap.to('.textShape', {
        duration: 2,
        fill: '#1D373F',
        morphSVG: ".Logo_Proper_Text"
    });
    logo_tl.add([firstAnimation, secondAnimation])
}

const changeViewBox = media_query => {
    media_query.matches ? viewBox = "-150 -180 2495 890" : viewBox = "-150 -350 3574 880"
    media_query.matches ? heading_Pos = [-511, -15] : heading_Pos = [-1540, 40];
    media_query.matches ? displayState = "none" : displayState = "block"
}

const moveLogo = () => {
    gsap.to(logo, {
        attr: { viewBox: viewBox },
        duration: 3
    })
    fadeInHeadingAndLinks();
}

const fadeInHeadingAndLinks = () => {
    gsap.to('.nav_links', {
        display: displayState,
        scale: 1,
        duration: 3
    })
    gsap.to('.logo_heading', {
        display: "block",
        x: heading_Pos[0],
        y: heading_Pos[1],
        // scale:1,
        duration: 3
    })
    gsap.to('.mobile_nav_sticky', {
        display: "block",
        scale: 1,
        duration: 5
    }, "+=.7")
}

const pageTransition = () => {
    var tl = gsap.timeline();
    tl.set('.loading_container img', {
        scale: 0.3
    })
    tl.to('.loading_container', {
        duration: 1.2,
        width: "100%",
        left: "0%",
        ease: "circ.out",
    })
        .to('.loading_container img', {
            scale: 0.6,
            duration: 1
        }, "-=1.2")

        .to('.loading_container', {
            duration: 1.2,
            width: "0%",
            right: "0%",
            ease: "circ.out",
        })
        .to('.loading_container img', {
            scale: 0.3,
            duration: 1.2
        }, "-=1.3")
}

// Helper Functions

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

// Initialization Methods
$(document).ready(() => {
    window.matchMedia("(max-width: 600px)").matches ? logo.attr('viewBox', '-350 -700 1274 1680') : logo.attr('viewBox', '-680 -380 2074 1080')
    var viewbox = window.matchMedia("(max-width: 600px)")
    changeViewBox(viewbox)
})

hamburger_display_button.onclick = () => {
    opened_nav_buttons.classList.toggle('open')
}

barba.init({
    sync: true,
    transitions: [{
        name: 'transition-base',
        preventRunning: true,
        timeout: 5000,
        async leave() {
            const done = this.async();
            pageTransition();
            await delay(1000);
            done();
        },
        async enter() {
            window.scrollTo(0, 0);
        },
    }],
    views: [
        {
            namespace: 'home',
            afterEnter() {
                homeInit()
                window.matchMedia("(max-width: 600px)").matches ? logo.attr('viewBox', '-350 -700 1274 1680') : logo.attr('viewBox', '-680 -380 2074 1080')
                let viewbox = window.matchMedia("(max-width: 600px)")
                changeViewBox(viewbox)
                logo_tl_func();
                hamburger_display_button.onclick = () => {
                    opened_nav_buttons.classList.toggle('open')
                }
            },
        },
        {
            namespace: 'about',
            afterEnter() {
                aboutInit()
                face_tl_func()
                scroll_p_tl_func()
                scroll_skills_tl_func()
                scroll_facts_tl_func()
            },
        }
    ],
});

// //Global Hooks 
// barba.hooks.leave(() => {
//     const done = this.async();
//     pageTransition();
//     await delay(1000);
//     done();
// })
// barba.hooks.enter(() => {
//     window.scrollTo(0, 0);
// })

and here's my about.js 

 

// Variable Declarations and Function Definitions
let factsContainer_sm = document.querySelector(".factsContainer_sm")

const aboutInit =() => {
    factsContainer_sm = document.querySelector(".factsContainer_sm")
    let head = document.getElementsByTagName('head')[0],
    link = document.createElement('link')
    link.rel = 'stylesheet'
    link.href= "../../Resources/CSS/about.css"
    head.appendChild(link);
}

const face_tl_func = () => {
    let face_tl = gsap.timeline(),
        paths = document.querySelectorAll('.My_Face path'),
        filledYellowElements = ['.Main_Hair_Part', '.Eyeball_2', '.Eyeball_1', '.Nostril_1', '.Nostril_2', '.Tongue_Part'],
        filledNavyElements = ['.Pupil_2', '.Pupil_1'];
    face_tl.set(filledNavyElements, { fill: 'unset' }),
        face_tl.set(filledYellowElements, { fill: 'unset' }),
        face_tl.fromTo(paths, { drawSVG: "0%" }, { duration: 1, drawSVG: "100% ", stagger: 0.15 })
    let firstAnimation = gsap.to(filledYellowElements, {
        duration: 2,
        ease: "slow",
        fill: '#F0C368'
    }, "-=.7"),
        secondAnimation = gsap.to(filledNavyElements, {
            duration: 2,
            ease: "bounce",
            fill: '#1D373F'
        }, "-=.7")
    face_tl.add([firstAnimation, secondAnimation])
}


const scroll_p_tl_func = () => {
    let scroll_tl = gsap.timeline({
        scrollTrigger: {
            trigger: '.content',
            start: "top center",
            end: "+=1000",
            markers: true,
            scrub: true
            // pin: true
        }
    })
    scroll_tl.to('.first', {
        transform: "rotateX(50deg) rotateZ(331deg) translateX(42px)",
        duration: .5,
    }),
        scroll_tl.to('.flag', {
            scale: 1
        }, '-=.1'),
        scroll_tl.addLabel("first_down")
    scroll_tl.to('.second', {
        transform: "rotateX(50deg) rotateZ(331deg) translateX(42px)",
        duration: 2,
    }, "first_down-=.1")
    scroll_tl.addLabel("second_down")
    scroll_tl.to('.third', {
        transform: "rotateX(50deg) rotateZ(331deg) translateX(42px)",
        duration: 2,
    }, "second_down-=.01")
}


const scroll_skills_tl_func = () => {
    let scroll_tl = gsap.timeline({
        scrollTrigger: {
            trigger: '.skillsContainer',
            start: "top center",
            markers: true,

        }
    }),
        barWidth = "",
        bars = [...document.querySelectorAll('.bar')]
    bars.map(bar => {
        barWidth = bar.dataset.width;
        let barAnimation = gsap.to(bar, {
            width: barWidth,
        }),
            percentageAniamtion = gsap.to('.percentage', {
                scale: 1,
            })
        scroll_tl.add([barAnimation, percentageAniamtion]);
    })

}

const scroll_facts_tl_func = () => {
    let scroll_tl = gsap.timeline({
        scrollTrigger: {
            trigger: '.factsContainer',
            start: "top center",
            // pin: true,
            scrub: true,
            end: "+=300",
            markers: true,
        }
    }),
        facts = [...document.querySelectorAll('.fact')]
    scroll_tl.to('.factsContainer h2', {
        scale: 1.5,
        duration: 1,
        ease: "slow"
    })
    scroll_tl.to(facts, {
        xPercent: -85 * (facts.length - 1),
        scrollTrigger: {
            trigger: ".factsContainer_sm",
            start: "center center",
            pin: true,
            // pinSpacing:false,
            markers: true,
            scrub: 1,
            snap: 1 / (facts.length - 1),
            // base vertical scrolling on how wide the container is so it feels more natural.
            end: () => `+=${factsContainer_sm.offsetWidth}`
        }
    });
}



// //Initialization Methods
aboutInit()
face_tl_func()
scroll_p_tl_func()
scroll_skills_tl_func()
scroll_facts_tl_func()

Here's the website homepage  - https://adamoceallaigh.netlify.app/

Here's the about page - https://adamoceallaigh.netlify.app/about.html

 

Appreciate all the help ye can give , if ye can , can ye check both mobile and desktop versions. 🤙

Cheers Adam 

Link to comment
Share on other sites

@adamoc when working with Barba there are a few things you have to get right in order to have everything working. Maybe it's best to double check everything below:

  • All the main elements that do not have to be reloaded each transition have to be inside the Barba wrapper, but not inside the Barba container. This means all your stylesheets, JS files, things that do not change like the header, footer, ...
  • Everything else goes inside the Barba container, i.e. the content that gets replaced everytime.
  • In my case I have one stylesheet and one JS file, which are just compiled assets from multiple files.
  • If I were you, I'd load all the JS file at the bottom of the file, just before the closing body tag.
  • All functions that have to run everytime need to be reinitialised in a Barba hook, which is probably almost all of them.
     

How I work is I write all animations and other functionality in seperate functions. Since I use WordPress the first thing I do when the site loads is init all those functions in a document ready, so in the Barba case, this means all functions have been initialised for all pages. Then I make sure that functions that need to be reinitialised every transition are included in the  'barba.hooks.afterEnter'.

 

Quote

Also I just have a few questions about your code above @mdelp , You define the function barbaInit() but where is this called and when ?? , also are those anim_about_in() and other view specific functions your initializers for the page or just animating the page in?? . Just want to clarify aswell , like i mentioned above if someone clicks a link that loads the about page again or something or goes directly to the about page the Barba animations are gone so therefore if you're reliant on Barba to initialize your scripts upon that specific page load then your scripts are not going to be initialized so do you call them independently like above in their seperate JS files too?? Last thing I want to clarify if i have a seperate stylesheet for each page , do I even need to include it in the seperate pages( about etc) as they will be redundant if barba is just gonna use my homepage as the one page for my application so would I be better off loading in all my stylesheets for all my seperate pages on the homepage or just put them to load in dynamically once the view with namespace ?? occurs??.

  • My barbaInit() function gets called on document.ready, together with all my other functions.
  • Those anim_about_in() are functions containing GSAP animations for the page in animations, so they only fire when entering a specific namespace.
  • You can init all your animations on the first Barba load to make sure if someone goes directly to the about page they see the animations, or do a conditional check with something like a .first-load class on the body to make sure all animations work both with and without a Barba transition.
  • For the stylesheet, you need to load all stylesheets because they are outside the Barba container and will not be replaced. Same goes for all other assets. Since all assets are loaded on the first load and don't have to be reloaded every page transition you have to include them all (not just on the homepage in case someone goes directly to another page). What I do is concatenate all sass into one css file and js into one file, and then have a preloader on the first load for when the assets are loading.

Hope this helps!

  • Like 3
Link to comment
Share on other sites

  • 3 months later...
On 2/14/2020 at 7:38 PM, akapowl said:

@mdelp

Looking good.

One thing I can tell you is, that the reason, why you do not need to reinit your scripts in this setup, is beacause the only script that you use (except for the barba setup)  is applied to the navigation module, which is outside of the <main data-barba="container"> . This means that it does not get removed and reapplied on every transition, but stays where it is and thus does not need to be re-initiated.

 

You will only need to re-initiate scripts that aim at elements, that are inside of  the <main data-barba="container"> and thus get removed and/or replaced.

I read all the above and tried to understand how I should reinitialize scripts. 
In my project, gsap scripts don't update when you move from one page to another. https://codepen.io/GeorgeDesign2020/project/editor/ZLrYEY

Link to comment
Share on other sites

@GeS You need to recreate any animations whose targets have been switched out and refresh ScrollTrigger when the page is done loading the new content. Maybe this article can help.

Link to comment
Share on other sites

45 minutes ago, ZachSaucier said:

@GeS Вам необходимо воссоздать любую анимацию, цели которой были отключены, и обновить ScrollTrigger, когда страница завершит загрузку нового контента. Возможно, эта статья поможет.

I will try!
thank you for the quick answer!

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.
×