Android / javascript - problem with window.innerWidth and window orientation. Take the arrow at the right time

I am trying to accurately capture the height and width of the mobile browser window when changing the orientation, but (on Android, I am testing) - when the orientation listener is launched and the function is called to capture the window height and width, the new size has not been accurately reflected yet, so I have to call arbitrary delay to get things to register their correct size. How can I handle this? Here is my code:

window.addEventListener(orientationEvent, function() {
    setTimeout("setViewport()", 500);
    //setViewport();
}, false);

function setViewport() { //Called each time orientation changes, including initial orientation
    viewportW = window.innerWidth; //only reports the accurate window size if the function is called on a delay
    viewportH = window.innerHeight;
}
+5
source share
1 answer

Use the resize event instead

window.addEventListener('resize', function() {
    viewportW = window.innerWidth;
    viewportH = window.innerHeight;
}, false);

, window.matchMedia, , :

var portrait=(window.matchMedia("(orientation: portrait)")?true:false);
0

All Articles