2
votes

I'm having trouble changing "viewport" "initial-scale" based on whether the iPhone is in portrait or landscape mode (and when the orientation changes).

I want the following in portrait mode:

<meta name="viewport" content="width=device-width, initial-scale=0.5">

I want the following in landscape mode:

<meta name="viewport" content="width=device-width, initial-scale=1.0">

And I want those scales after there's an orientation change.

Here are my two unsuccessful efforts:

<meta name="viewport" content="width=device-width, initial-scale=0.5">
<script type="text/javascript">
    if($(window).width() < 900)
    {
        x=1;
        if(x==1)
        {
            $('meta[name=viewport]').remove();
            $('head').append('<meta name="viewport" content="width=device-width, initial-scale=1.0">');
            x=0;
        };
    };
</script>

https://stackoverflow.com/a/15522332

<script>
        if(screen.width>=1){
            $('head').append('<meta name="viewport" content="width=device-width, initial-scale=0.5">');
        } else {
            $('head').append('<meta name="viewport" content="width=device-width, initial-scale=0.5">');
        }
        $(window).on("orientationchange",function(){
          if(window.orientation == 0) // Portrait 
          {
            $('head').append('<meta name="viewport" content="width=device-width, initial-scale=0.5">');
          } else // Landscape 
          {
            $('head').append('<meta name="viewport" content="width=device-width, initial-scale=1.0">');
          }
        });
</script>

Meta Viewport just on Portrait?

I would get rid of the screen width part if I could, and just focus on whether the page is in portrait or landscape.

1

1 Answers

1
votes

You can use window.matchesMedia along with the orientationchange event on the window.

const meta = document.createElement('meta');
meta.name = "viewport";
if (window.matchMedia("(orientation: portrait)").matches) {
   meta.content = "width=device-width, initial-scale=0.5";
} else {
   meta.content = "width=device-width, initial-scale=1.0";
}
document.head.appendChild(meta);
window.addEventListener("orientationchange", function() {
  if(window.orientation == 0){
     meta.content = "width=device-width, initial-scale=0.5";
  } else {
     meta.content = "width=device-width, initial-scale=1.0";
  }
}, false);