Sunday, 19 June 2011

Android Javascript Defect with orientationchange?

Working on a mobile web enabled site using JQuery Mobile, I've found a peculiar behavior in Android devices on all browsers: JQuery Mobile provides some extra events for mobile devices one of which is orientation change.

This event fires whenever the user changes the orientation of their device. The event that fires with it contains a number of additional fields, one of which is orientation which contains either the value 'portrait' or 'landscape' depending on which way the device has been turned.

You bind to the event using the following syntax:

$(window).bind("orientationchange", callback);

where 'callback' is your callback function. On iOS devices, evaluating e.orientation (the event field) returns 'landscape' when I turn the phone horizontally and 'portrait' when I turn it vertically. On Android devices, however, the event seems to fire as the orientation change takes place but before it has actually changed any properties of the window. As a result, you get the opposite values back. Likewise if you take a read on the screen size.

This provides an irritating issue for anyone trying to re-draw their screen on orientation change as any size parameters that need to be applied to page elements will go in based on the previous dimensions of the window rather than the ones you are going into.

The workaround I have found is to bind to window.resize instead. This has the advantage of firing at the same time on both platforms, but you lose the custom orientation field in the event and are forced to rely instead on old-fashioned reads of screen dimensions. In many cases this will need to be done regardless as elements are sized to fit new spaces, so it might not be such a great loss to lose the orientation. On the other hand, JQuery Mobile allows many elements to be re-styled easily using this attribute and without it we are stuck working through a lot more code.

No comments:

Post a Comment