Dynamic change of viewport meta tag

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

Assuming I have the following viewport on the page for viewing 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, of type full version which, when clicked, calls a JavaScript (or jQuery) function that changes the width of the viewport to 1024 pixels wide. It change in <meta> property, via script, already changes the page view immediately or need to do a reload ?

Another thing: should the viewport with width set in pixels contain px or just the number (e.g. width=1024, or width=1024px,)?

Author: Sam, 2017-11-11

1 answers

This answer applies to mobile devices.

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

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

insert the description of the image here

Result after clicking the button full version :

insert the description of the image here

However, the opposite works perfectly, i.e. changing the fixed value viewport (width=1024) to mobile mode (width=device-width...).

Conclusion:

You need to refresh the page so that the content of the page fits viewport. In this case, you would need to save the new value of 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 from 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 viewport, one should not use px (as examples above).

 0
Author: Sam, 2017-11-13 18:45:10