javascripthtmlmobile-safari

Can we detect if resize event is triggered by zooming on mobile?


I was using a function triggered by resize to dynamically adjust the layout of my page, which I use to make sure my page looks good when users expand/reduce their address bars on mobile. But now I found that sometimes resize would also be triggered when user zoom in or out using two fingers or double taps, in which case I don't want the function related to resize event to be triggered.

Is there a way to detect whether the resize event is triggered by zooming?


Solution

  • Been struggling with it on iPhone recently. I've found this event and works well on iPhone :

    visualViewport.addEventListener("resize", () => {
    
    });
    

    Reference: https://developer.mozilla.org/en-US/docs/Web/API/VisualViewport/resize_event

    My complete solution is a mix of 3 events to work on all major browsers:

    window.addEventListener("resize", ()=> {});
    if(visualViewport) visualViewport.addEventListener("resize", ()=> {});
    window.screen.orientation.addEventListener("change", ()=> {});