Use Javascript to Change Viewport Width Depending on the Window Size

Sometimes for a responsive website you might want to apply the desktop stylesheet also on tablets and mobile devices in landscape mode. When using media queries to style a website based on the device width, a typical viewport meta tag would be:

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

This will force a browser to render a 980px wide website on an iPad with a horizontal scrollbar because the device width of an iPad is 768px. However, if you don’t specify the viewport width (width=device-width) it will use the default viewport value of 980px which will make it ignore all media queries that you have specified in the stylesheet.

Ideally we would like to define a viewport value of 980px when the device width is above 768px (which is also mostly landscape orientation) and force browsers to ignore media queries:

<meta name="viewport" content="width=980" />

but set it to device-width if the device width is 768px or lower:

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

so that on devices with the actual viewport smaller than 768px the browser applies the correct media queries and styles.

Use Javascript to Change Viewport Meta

The solution is to change the viewport definition based on the device width as reported by screen.width. In order to do that we need to add a unique identifier to our meta definition:

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

and then use the following snippet of Javascript to actually change the viewport meta value based on window width:

// Store the meta element
var viewport_meta = document.getElementById('viewport-meta');

// Define our viewport meta values
var viewports = {
		default: viewport_meta.getAttribute('content'),
		landscape: 'width=990'
	};

// Change the viewport value based on screen.width
var viewport_set = function() {
		if ( screen.width > 768 )
			viewport_meta.setAttribute( 'content', viewports.landscape );
		else
			viewport_meta.setAttribute( 'content', viewports.default );
	}

// Set the correct viewport value on page load
viewport_set();

// Set the correct viewport after device orientation change or resize
window.onresize = function() { 
	viewport_set(); 
}

Leave a Reply