Jump to content


Triggering different timelines at different breakpoints with matchmedia()

Moderator Tag

Recommended Posts

I'm trying to trigger different timelines at different breakpoints using the window.matchmedia(); method.


I've attempted to put together a potential example here:


const box = document.querySelector(".box");
const change = document.querySelector(".change");

const mqs = [
  window.matchMedia("(min-width: 600px)"),
  window.matchMedia("(min-width: 768px)"),
  window.matchMedia("(min-width: 1024px)")

const tl = gsap.timeline({
  paused: true;

if (mqs[0].matches) {
  tl.to(box, { backgroundColor: "green" });
} else if (mqs[1].matches) {
  tl.to(box, { backgroundColor: "pink" });
} else {
  tl.to(box, { backgroundColor: "black" });

function playTl() {

change.addEventListener("click", playTl);

My idea is to have the change button trigger the animations.


Is it a little more complex that this approach?


Having dug around in the forums it seems media queries plus gsap tends to throw up a number of complex solutions, I was hoping for something a little more simpler.


Here's a Codepen also: 

See the Pen 94c0b1c73f770d36f1103f615ac3e917 by abbasarezoo (@abbasarezoo) on CodePen

Link to comment
Share on other sites

Hey abbasarezoo and welcome to the GreenSock forums. What you're doing above won't work because on resize it would keep adding to the same timeline without clearing out the old tweens. Why not just recreate the animation instead? I might set it up along the lines of this:

See the Pen NWNeRBr by GreenSock (@GreenSock) on CodePen

Link to comment
Share on other sites

That seems to do the trick. Thanks for looking into this for me, I appreciate it.

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.