5

I wrote the code below to check my mobile screen height when I rotate it to Portrait or Landscape.

window.addEventListener("orientationchange", function(event) {
  rotateScreen();
}, false);

function rotateScreen() {
  alert(window.orientation)
  alert($(window).height())
}

When I rotate it to Portrait, I get 0, 294. When I rotate it to Landscape, I get 90, 419. The figure is reversed, I have tried to wrap it in $(document).ready() but it does not work.

$(document).ready(function(){
  alert($(window).height())
})

It looks like that when I rotate the mobile to Portrait, I get the height of Landscape, and when I rotate the mobile to Landscape, I get the height of Portrait. Can someone suggest how to fix it?

Thanks

dda
  • 6,030
  • 2
  • 25
  • 34
Charles Yeung
  • 38,347
  • 30
  • 90
  • 130

2 Answers2

11

The resize event gets triggered after the orientationchange event. However resize can also get triggered by other things such as showing the virtual keyboard.

So to get round this we can listen first for an orientationchange, once that occurs we can then add a resize listener. Once the orientationchange has completed it will fire our resize event. Once completed we then remove the resize listener to prevent it being fired in error

$(window).on('orientationchange', function() {
    var orientationChange = function(evt) {
        rotateScreen();
        $(window).off('resize', orientationChange);
    }
    $(window).on('resize', orientationChange);
});

This effectively creates a kind of pseudo post:orientationChange event. (I would probably avoid using timeouts if you can)

Andy Polhill
  • 6,858
  • 2
  • 24
  • 20
2

Adding setTimeout could solve the problem, please try the code below:

function rotateScreen() {
    window.setTimeout(function() {
       alert(window.orientation)
       alert($(window).height())
    }, 500);

}
Charles Yeung
  • 38,347
  • 30
  • 90
  • 130
  • 2
    I believe this is a cheap hack and you can't guarantee that it's going to happen. Also it will appear slow when it's quicker. The answer by Andy Polhill is a much better solution as it guarantees both at the right time. – creamcheese Jul 10 '14 at 13:31
  • @DominicWatson the problem with Andy solution is that it triggers before the resize animation ends (and shows the browser address bar on both iOS and Android) - so it gives a bigger innerHeight than supposed. And adding logic for that ends up being as cumbersome if not worse than the timeout. – Tom Roggero Jan 24 '19 at 17:13