Charles Yeung
Charles Yeung

Reputation: 38815

Getting wrong screen height when trigger orientationchange event

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

Upvotes: 5

Views: 3407

Answers (2)

Andy Polhill
Andy Polhill

Reputation: 7368

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)

Upvotes: 11

Charles Yeung
Charles Yeung

Reputation: 38815

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

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

}

Upvotes: 2

Related Questions