Jump to content


Change Tween Animation Vars / Properties with a Ternary Operator Dependent on Window Size

Warning: Please note

This thread was started before GSAP 3 was released. Some information, especially the syntax, may be out of date for GSAP 3. Please see the GSAP 3 migration guide and release notes for more information about how to update the code to GSAP 3's syntax. 

Recommended Posts



I'm trying to use the ternary operator on a tween to have two different colours depending on the window size of part of a menu after being clicked.


The actual animation is part of an SVG timeline, but I've simplified it down in the codepen with one div.


What I'm trying to do is use the ternary operator to change the color dependent on window size.


In the past I've used it on animation duration values like this:


.to("#square", window.innerWidth > 736 ? 1.5 : 1, {opacity: 1})


I can't seem to get it work on tween property values inside the curly braces though?


Doing the following won't work:


.to("#square", 1, {window.innerWidth > 736 ? background: "red", : background: "blue" })


Is there a simple way within a timeline to have an if/else or ternary operator on the property:value pairs of a tween, that I can change dependent on window size?


The only other option I guess would be to duplicate the entire timeline in another if/else statement


See the Pen oamVMa by emilychews (@emilychews) on CodePen

Link to comment
Share on other sites

The first part inside the object is key and second part is value, so you need to use ternary operator in value part.


.to("#square", 1, {backgroundColor: window.innerWidth > 736 ?  "red" : "yellow" });


See the Pen aRMdqM?editors=0010 by Sahil89 (@Sahil89) on CodePen


Also, by declaring timeline outside of function you were adding all tweens to same timeline even though you won't be reusing them.

  • Like 8
Link to comment
Share on other sites

Thanks Sahil, that's great.  My general JS knowledge isn't yet what I need it to be. Much appreciated.

  • Like 2
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.