This approach is unfortunately never going to work, because the variable that stores the content attribute of the viewport meta tag (in this case defaultContent
) is always going to fetch the current value. The only way to make this work is to define defaultContent
explicitly, as I have done with customContent
.
Firstly, let's see why the initial approach doesn't work:
Try this code on your console
while visiting Smashing Magazine:
defaultContent = jQuery('meta[name=viewport]').attr('content'); // store the current value in a global variable
console.log(defaultContent);
function setV(){
// override the global variable value with a scoped variable
var customContent = 'width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, user-scalable=0';
jQuery('meta[name=viewport]').attr('content', customContent);
console.log('Set viewport content to: ' + customContent);
}
function resetV(){
jQuery('meta[name=viewport]').attr('content', defaultContent);
console.log('Reset viewport content to: ' + defaultContent);
}
Make sure you test setV();
or resetV();
directly on the console, by typing them and clicking Run
again. As you can see, it won't work because defaultContent
is set to fetch a dynamic value, that gets changed by the setV()
function.
To make it work
As I already mentioned, if you want it to work on your site, you could define a new variable with the defaultContent
value (default content attribute of the viewport meta tag), so you have it properly stored from the start - like so:
defaultContent = 'width=device-width, initial-scale=1.0';
customContent = 'width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, user-scalable=0';
function setV(){
jQuery('meta[name=viewport]').attr('content', customContent);
console.log('Set viewport content to: ' + customContent);
}
function resetV(){
jQuery('meta[name=viewport]').attr('content', defaultContent);
console.log('Reset viewport content to: ' + defaultContent);
}
Not that I changed $
to jQuery
to avoid conflict at Smashing Magazine.