Dynamic change of meta viewport tag

Asked

Viewed 140 times

1

It is possible to change the viewport of a page and have immediate effect without having to update it?

Supposing I have the following viewport on the page to display on mobile devices (smartphones and tablets):

<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />

So I have a button at the bottom of the page, like Full version which, when clicked, calls a Javascript (or jQuery) function that changes the width of viewport to 1024 pixels wide. This change in the property of <meta>, via script, already changes the page view immediately or need to make a Reload?

Another thing: the viewport with width defined in pixels, must contain px or just the number (ex., width=1024, or width=1024px,)?

1 answer

0


This response applies to mobile devices.

I realized that by dynamically changing the viewport for a fixed width, the screen resolution changes, but the content does not adapt to the width.

Image with viewport="device-width...":

inserir a descrição da imagem aqui

Result after clicking the button Full version:

inserir a descrição da imagem aqui

However, otherwise works perfectly, ie changing the viewport fixed-value (width=1024) for mobile mode (width=device-width...).

Completion:

You need to refresh the page so that the page content fits the viewport. In this case, the new value of the viewport in a variable (e.g., SESSION, localStorage...) and refresh the page and render with the new viewport.

Example using SESSION with PHP:

<?php
if( $_SESSION['viewport'] == "desktop"){
?>
<meta name="viewport" content="width=1024...
<?php
}else{
?>
<meta name="viewport" content="device-width...
<?php
}
?>

Example using localStorage javascript:

<script>
if( localStorage.viewport == "desktop"){
   document.write('<meta name="viewport" content="width=1024...');
}else{
   document.write('<meta name="viewport" content="device-width...');
}
</script>

When setting a value width in the viewport, should not be used px (as examples above).

Browser other questions tagged

You are not signed in. Login or sign up in order to post.