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
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With