Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 365
Charles Yeung Avatar asked Dec 16 '22 21:12

Charles Yeung


1 Answers

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)

like image 186
Andy Polhill Avatar answered Dec 21 '22 10:12

Andy Polhill