Can I change the viewport meta tag in mobile safari on the fly?

Pepper picture Pepper · Aug 28, 2010 · Viewed 105.3k times · Source

I have an AJAX app built for mobile Safari browser that needs to display different types of content.

For some content, I need user-scalable=1 and for other ones, I need user-scalable=0.

Is there a way to modify the value of the content attribute without refreshing the page?

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

Answer

markquezada picture markquezada · Nov 4, 2010

I realize this is a little old, but, yes it can be done. Some javascript to get you started:

viewport = document.querySelector("meta[name=viewport]");
viewport.setAttribute('content', 'width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0');

Just change the parts you need and Mobile Safari will respect the new settings.

Update:

If you don't already have the meta viewport tag in the source, you can append it directly with something like this:

var metaTag=document.createElement('meta');
metaTag.name = "viewport"
metaTag.content = "width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0"
document.getElementsByTagName('head')[0].appendChild(metaTag);

Or if you're using jQuery:

$('head').append('<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0">');