I'm using GSAP / Tweenmax for some animations and I'm very close to where I want the animations to be. I have two different timelines - one for mobile, one for desktop. How can I make sure they each play regarding the window width and also if screen is resized clear to the final state of each animation. I tried using some window width resize calls but now the animations play everytime the browser width is moved at all and I see why with how I'm calling the functions, what is the best way to do this? thanks! :)
js:
$(function () {
function animations() {
if ($(window).width() > 768) {
heroAnimation.play(0);
} else {
heroAnimation.pause(0);
}
}
function animationsMobile() {
if ($(window).width() <= 767) {
heroAnimationMobile.play(0);
} else {
heroAnimationMobile.pause(0);
}
}
$(window).resize(animations);
animations();
$(window).resize(animationsMobile);
animationsMobile();
});
You should keep track of the state and only restart the animation if the state changes. Also only use one function, no need for two:
var state = "";
function animations() {
var newState = state;
if (innerWidth > 768) {
newState = "big";
} else {
newState = "small";
}
if(newState !== state) {
if(newState === "big") {
heroAnimation.play(0);
heroAnimationMobile.pause(0);
} else {
heroAnimation.pause(0);
heroAnimationMobile.play(0);
}
state = newState;
}
}
document.addEventListener("resize", animations);
animations();
By the way, you should totally use GSAP 3! It has a smaller file size, sleeker API, and a bunch of new features!
Also, you're more likely to get an even faster response and additional insight over on the GreenSock forums.