Search code examples
viewporttablet

How to Dynamically set your viewport to the Page Limits


I've got a page that is 1200px wide (but this can change). I've got a viewport that I can't change that is:

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

I'm trying to write a script where, if you come to the page with a device that is more than 601px wide and less than 1025px wide the screen will zoom out to the page width. Currently the device will load the page and show the first 768px then the user has to zoom out to see the remaining 1200px.

This is somewhat what I want:

if(window.innerWidth > 600 && window.innerWidth < 1024){
  var defaultDeviceWidth = window.innerWidth;
  var defaultPageWidth = document.getElementById('wrapper').offsetWidth;
    if(defaultDeviceWidth < defaultPageWidth){
    document.querySelector('meta[name="viewport"]').content = 'initial-scale='+
      (defaultDeviceWidth/defaultPageWidth)+
      ', maximum-scale='+(defaultDeviceWidth/defaultPageWidth)+
      ', user-scalable=yes';
  }
}

Which will output:

<meta name="viewport" content="initial-scale=0.64, maximum-scale=0.64, user-scalable=yes">

Problem with this is, maximum-scale zooms the view out but doesn't allow the user to zoom in if they want to.

Essentially:

I want tablets to zoom out to the page limits, as if you did the pinch out as far as it'll go using javascript.


Solution

  • I think one popular method to best fit the website layout for viewers from all devices are through the use of responsive classes (media queries, bootstrap, jquery-mobile, etc. )

    Other ways to load dynamic CSS styles can be using refresh trigger to load specific *.css in different device resolutions.

    Have you thought about using dynamic if-else to echo different viewport meta tag once you detected the device width in advance before converting to HTML and show in client side?