Reset Viewport Zoom on iOS10 with Javascript
Also, I found that setting the value of meta viewport content, it only has any effect only once. If you try to zoom out multiple times, you might need to apply random values.
function pinchOut() {
appliedScale = 1 - Math.random()*0.01;
document.querySelector('meta[name="viewport"]').setAttribute('content', "width=device-width, initial-scale=" + appliedScale);
}
Issues
attr()
is not a JavaScript function. It is a jQuery method.- you are using
viewportmeta
to get themeta
tag and then try to set attribute toviewport
variable, which is not declared.
Solution
Since you are using JavaScript, use the setAttribute
method instead.
Syntax :
const viewportmeta = document.querySelector('meta[name=viewport]');
viewportmeta.setAttribute('content', "initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0");
Snippet
let viewportmeta = document.querySelector('meta[name="viewport"]');
viewportmeta.setAttribute('content', "initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0");
console.log(document.querySelector('meta[name="viewport"]'));
<meta name="viewport" />
It will set the content
on if the meta[name=viewport]
is present in the page.
If you don't have a <meta name="viewport".../>
in the page, create one, use setAttribute
to set name=viewport
and append it to head.
Working Snippet
let viewportmeta = document.querySelector('meta[name="viewport"]');
if(viewportmeta===null){
viewportmeta = document.createElement("meta");
viewportmeta.setAttribute("name","viewport");
document.head.appendChild(viewportmeta);
viewportmeta = document.querySelector('meta[name="viewport"]');
}
viewportmeta.setAttribute('content', "initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0");
console.log(document.querySelector('meta[name="viewport"]'));