0

Because of some necessary parts of this concept, it's needed that the viewportratio is >=1:1 but also <=2:1.

When it isn't a value between 1:1 and 2:1, there should a div container fade in, where I have a text message in it. But when the viewport ratio is then corrected to a fitable value, it should fade out automatically.

This check should happen every time, when the Viewport dimension changes, not only when the page is loading.

Could someone help me with that problem?

3 Answers3

0

Check out this JSfiddle: https://jsfiddle.net/ChefGabe/e1vfhyuw/ (you can resize the output window to simulate a page resize)

Lines 1 and 2 are Event listeners. DOMContentLoaded is fired after the HTML is parsed on page load. resize is fired on resize (duh).

(Edit: DOMContentLoaded won't work in JSfiddle, but it should work in a real scenario)

I used this StackOverflow question to get the width and height of the browser.

Hope that helped!

Community
  • 1
  • 1
Gabe Rogan
  • 3,343
  • 1
  • 16
  • 22
0

To check the size of the window, listen to the onresize event fired by the window object, resize event can fire multiple times in short interval, so it is best to only execute the callback after a certain amount of time has passed, hence the throttle() function

function throttle(interval, fn) {
  var inProgress;
  return function() {
    if (inProgress) {
      clearTimeout(inProgress);
    }
    else {
      inProgress = setTimeout(fn, interval);
    }
  }
}

var onResize = throttle(500, function() {
  if ((screen.availWidth / screen.availHeight) <= 2)
    fadeIn();
  else
    fadeOut();
});
window.addEventListener('resize', onResize, false);
Trash Can
  • 6,608
  • 5
  • 24
  • 38
0

You don't actually even need JavaScript for this. I'd recommend solving this through pure CSS media query. There's one for aspect ratio, so we'd use something like

@media screen and (min-aspect-ratio: 1/1) and (max-aspect-ratio: 2/1) { ... }

And inside the query you can then trigger the message's visibility.

@media screen and (min-aspect-ratio: 1/1) and (max-aspect-ratio: 2/1) {
    .ratio-message {
        /* Whatever custom animation to reveal the message like opacity or display */
        transform: translateX(0);
    }
}

And an example on jsfiddle.

kano
  • 5,626
  • 3
  • 33
  • 48