Last active
October 16, 2023 12:30
-
-
Save OysteinAmundsen/9e6b2ebdf8264ec0e25a0540661949bc to your computer and use it in GitHub Desktop.
Prevent zoom on iOS when input fields are focused
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Directive, HostListener, signal } from '@angular/core'; | |
@Directive({ selector: '[flxInput]', standalone: true }) | |
export class PreventZoomDirective { | |
zoomDisabled = signal(false); | |
hasFocus = signal(false); | |
get meta() { | |
return Array.from(document.getElementsByTagName('meta') || []).find(m => m?.getAttribute('name') === 'viewport'); | |
} | |
@HostListener('pointerover') | |
zoomDisable() { | |
const content = this.meta?.getAttribute('content'); | |
if (!this.zoomDisabled() && content != null) { | |
this.meta?.setAttribute('content', `${content}, maximum-scale=1`); | |
this.zoomDisabled.set(true); | |
} | |
} | |
@HostListener('pointerout') | |
pointerOut() { | |
if (!this.hasFocus() && this.zoomDisabled()) { | |
// Pointer moved out of the input without focus being added. | |
this.zoomEnable(); | |
} | |
} | |
@HostListener('focus') | |
focus() { | |
this.zoomDisable(); | |
this.hasFocus.set(true); | |
} | |
@HostListener('blur') | |
zoomEnable() { | |
const content = this.meta?.getAttribute('content'); | |
if (this.zoomDisabled() && content != null) { | |
this.meta?.setAttribute('content', `${content.replace(', maximum-scale=1', '')}`); | |
this.zoomDisabled.set(false); | |
this.hasFocus.set(false); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment