Search code examples
androidjqueryzoomingcenter

Get webpage center coordinates on tablet devices using JavaScript


I'm trying to compute the viewport geometric center on a webpage, rendered with Tablet devices (iOS and Android), ie the actual CENTER of the viewport (what you see) according to current translation and current zoom level - don't want the center of the document itself, I want the center of the screen what I'm viewing.

The problem is that this calculation is does not take into account any kind of zoom (an then) translation.

On iOS, I've tried with some of these answers, on the question detecting pinch to zoom on iOS, I was able to catch the event "OnZoom" but didn't get any value, though.

On Android, I can't even catch any event related to zoom. I'm aware of touchmove and touchstart events, but how can I distinguish then in order to get zoom (and zoom value)

I'm using jQuery 1.7.2 library.


Solution

  • I have made a demo page which is confirmed to work on iPhone iPad, Samsung Galaxy Tab 10. I have only attached the click event on a huge div, so tap on the screen after zooming to update the display.

    The calculation is very simple, use screen.width/window.innerWidth to get the zoom level. screen.width will always be in device pixels and window.innerWidth is always in css pixels, which also take the zoom into account.

    Further calculation is simple math:

    // round the result down to avoid "half pixels" for odd zoom levels
    Math.floor(window.scrollY + window.innerHeight/2);
    Math.floor(window.scrollX + window.innerWidth/2);
    

    To check whether the user is zooming, attach the listener to window.resize and window.scroll which will fire after orientationchange hiding the address bar and zooming.

    Here's my demo JavaScript:

    var dot = document.getElementById("dot");
    document.getElementById("main").addEventListener("click", function(e) {
        var zoom = screen.width / window.innerWidth;
        alert("zoom: " + zoom + "\n" + "ScrollY: " + window.scrollY);
    
        dot.style.top = Math.floor(window.scrollY + window.innerHeight/2 - 5) + "px";
        dot.style.left = Math.floor(window.scrollX + window.innerWidth/2 - 5) + "px";
    
    }, false);