N. Thompson
N. Thompson

Reputation: 95

How can I define a variable depending on the width of the screen?

I'm animating based on scroll position using TweenMax. The position at which I want to animate changes depending on the screen size. Is it possible to have a variable change based on the width of the screen?

I'm fairly new and using a lot of copy/paste solutions. I have two rectangular divs beside each other that flip over like cards to display information on the back. When viewed on a mobile screen, these cards stack vertically instead of beside each other. This then changes the point at which I want to animate the flipping of the card.

The solution I've landed on is to change var sceneStart depending on a media query. This is just an idea for a solution to the problem.

This is what I have tried to no success.

var sceneStart2;
if (window.matchMedia("(max-width: 480px)")) {
  sceneStart2 = 3500
} else {
  sceneStart2 = 2000
}

Expected result is on a large screen while divs are beside each other, card2 flips at 2000 but on a mobile screen card flips at 3500.

Actual result is that it breaks the flip entirely and doesn't function.

Upvotes: 0

Views: 1853

Answers (1)

SimpleJ
SimpleJ

Reputation: 14798

You need to check the matches property of the MediaQueryList returned by matchMedia:

var sceneStart2;
if (window.matchMedia("(max-width: 480px)").matches) {
  sceneStart2 = 3500
} else {
  sceneStart2 = 2000
}
console.log(sceneStart2);

Check out this article on MDN for more info about matchMedia.

If you want this to update when the window resizes, you could move this logic into a function that gets called initially and on every window resize event:

var sceneStart2;

calcSceneStart2();
window.addEventListener('resize', calcSceneStart2);

function calcSceneStart2() {
  if (window.matchMedia("(max-width: 480px)").matches) {
    sceneStart2 = 3500
  } else {
    sceneStart2 = 2000
  }
  console.log(sceneStart2);
}

Upvotes: 2

Related Questions