I have the following code which will update the background image of my page when you rotate it a certain way:
window.onorientationchange = function() {
var orientation = window.orientation;
switch (orientation) {
case 0:
$(".bg-img").css("background-image", "url(" + portrait + ")");
break;
case 90:
$(".bg-img").css("background-image", "url(" + landscape + ")");
break;
case -90:
$(".bg-img").css("background-image", "url(" + landscape + ")");
break;
};
};
This works, but when the page is rotated, it takes a few seconds to load the new image, and causes the page to look odd.
Is there anyway to detect that the orientation is changing, instead of changed? Something like willAnimateFirstHalfOfRotationToInterfaceOrientation?
The
deviceorientationevent fires with updates to the current position of the device. Here’s a demo.Note that this only works on iPhone ≥ 4 and iPad ≥ 2. Older Apple hardware doesn’t have a gyroscope.
The event also worked on my Galaxy Nexus Android 4 device in Chrome and the stock browser.
You could also preload your background images so that the switch occurs instantly.