Jump to content
Search Community

Correct implementation of matchMedia in Nuxt?

Liam_hyperisland test
Moderator Tag

Go to solution Solved by Rodrigo,

Recommended Posts

  • Solution

Hi,

 

The main issues is that you are wrapping your GSAP MatchMedia instance with a GSAP Context instance and your breakpoints.

 

There is no need for using GSAP Context when you use GSAP MatchMedia. MatchMedia is a Context instance with responsive super powers, so you can revert that particular instance and everything should work in the same way. You can also add a scope in the add() method or you can use a scope in a toArray() utility method like this:

onMounted(() => {
  const boxes = gsap.utils.toArray('.box', main.value);// <- Scope for the selector

  mm.add('(min-width: 768px)', () => {
    tl = gsap
      .timeline()
      .to(boxes[0], { color: 'red' })
      .to(boxes[1], { x: 300 }, '<')
      .to(boxes[2], { y: 300 })
      .reverse();
  });

  mm.add('(max-width: 767px)', () => {
    tl = gsap
      .timeline()
      .to(boxes[0], { x: 120, rotation: 360 })
      .to(boxes[1], { x: -120, rotation: -360 }, '<')
      .to(boxes[2], { y: -200 })
      .reverse();
  });
});

Since in this case the elements with that class are the same in every screen size there is no need to add that in the add() method. If the elements do change based on the screen size, then you can pass a scope to the add() method:

let mm = gsap.matchMedia();

mm.add("(min-width: 768px)", () => {
  // ...
}, main.value); // <- Scope!

Then these breakpoints are not going to work as you expect for a couple of pixels (299 and 300):

mm.add('(min-width: 299px)', () => {
});

mm.add('(max-width: 300px)', () => {
});

Those will overlap because you're telling GSAP do this when the size of the screen is more than 299 pixels, and do that until the width of the screen is  between 0 and 300 pixels. The first one will run while the first one is still active. When you reach 300 pixels width both are active and overlapping.

https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_media_queries/Using_media_queries

https://medium.com/@banuriwickramarathna/min-width-max-width-media-queries-994e2ec5fca3

 

Here is a fork of your example:

https://stackblitz.com/edit/nuxt-starter-cuqke7?file=pages%2Findex.vue

 

Hopefully this helps.

Happy Tweening!

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.
×
×
  • Create New...