Skip to content

Instantly share code, notes, and snippets.

@Loac-fr
Forked from zachleat/gist:2008932
Created July 28, 2017 13:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Loac-fr/220380c24a567b82a44e1bbf59a7d0fa to your computer and use it in GitHub Desktop.
Save Loac-fr/220380c24a567b82a44e1bbf59a7d0fa to your computer and use it in GitHub Desktop.
Prevent zoom on focus
// * iOS zooms on form element focus. This script prevents that behavior.
// * <meta name="viewport" content="width=device-width,initial-scale=1">
// If you dynamically add a maximum-scale where no default exists,
// the value persists on the page even after removed from viewport.content.
// So if no maximum-scale is set, adds maximum-scale=10 on blur.
// If maximum-scale is set, reuses that original value.
// * <meta name="viewport" content="width=device-width,initial-scale=1.0,maximum-scale=2.0,maximum-scale=1.0">
// second maximum-scale declaration will take precedence.
// * Will respect original maximum-scale, if set.
// * Works with int or float scale values.
function cancelZoom()
{
var d = document,
viewport,
content,
maxScale = ',maximum-scale=',
maxScaleRegex = /,*maximum\-scale\=\d*\.*\d*/;
// this should be a focusable DOM Element
if(!this.addEventListener || !d.querySelector) {
return;
}
viewport = d.querySelector('meta[name="viewport"]');
content = viewport.content;
function changeViewport(event)
{
// http://nerd.vasilis.nl/prevent-ios-from-zooming-onfocus/
viewport.content = content + (event.type == 'blur' ? (content.match(maxScaleRegex, '') ? '' : maxScale + 10) : maxScale + 1);
}
// We could use DOMFocusIn here, but it's deprecated.
this.addEventListener('focus', changeViewport, true);
this.addEventListener('blur', changeViewport, false);
}
// jQuery-plugin
(function($)
{
$.fn.cancelZoom = function()
{
return this.each(cancelZoom);
};
// Usage:
$('input:text,select,textarea').cancelZoom();
})(jQuery);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment