I am attaching a listener to the orientationchange
event:
window.addEventListener('orientationchange', function () {
console.log(window.innerHeight);
});
I need to get the height of the document after the orientationchange
. However, the event is triggered before the rotation is complete. Therefore, the recorded height reflects the state before the actual orientation change.
How do I register an event that would allow me to capture element dimensions after the orientation change has been completed?
Orientation change needs a delay to pick up on the new heights and widths. This works 80% of the time.
Gajus' and burtelli's solutions are robust but the overhead is high. Here is a slim version that's reasonably fast in 2017, using
requestAnimationFrame
:Use it like this:
I also faced the same problem. So I ended up using:
I used the workaround proposed by Gajus Kuizunas for a while which was reliable albeit a bit slow. Thanks, anyway, it did the job!
If you're using Cordova or Phonegap I found a faster solution - just in case someone else faces this problem in the future. This plugin returns the correct width/height values right away: https://github.com/pbakondy/cordova-plugin-screensize
The returned height and width reflect the actual resolution though, so you might have to use window.devicePixelRatio to get viewport pixels. Also the title bar (battery, time etc.) is included in the returned height. I used this callback function initally (onDeviceReady)
In your orientation change event handler you can then use:
to get the innerHeight right away. Hope this helps someone!
There is no way to capture the end of the orientation change event because handling of the orientation change varies from browser to browser. Drawing a balance between the most reliable and the fastest way to detect the end of orientation change requires racing interval and timeout.
A listener is attached to the
orientationchange
. Invoking the listener starts an interval. The interval is tracking the state ofwindow.innerWidth
andwindow.innerHeight
. Theorientationchangeend
event is fired whennoChangeCountToEnd
number of consequent iterations do not detect a value mutation or afternoEndTimeout
milliseconds, whichever happens first.I am maintaining an implementation of
orientationchangeend
that extends upon the above described logic.Use the resize event
The resize event will include the appropriate width and height after an orientationchange, but you do not want to listen for all resize events. Therefore, we add a one-off resize event listener after an orientation change:
Javascript:
jQuery:
Do NOT use timeouts
Timeouts are unreliable - some devices will fail to capture their orientation change within your hard-coded timeouts; this can be for unforeseen reasons, or because the device is slow. Fast devices will inversely have an unnecessary delay in the code.