One hassle with working with mobile websites is inconsistency between how the device reports the screen's width and height. James Pearce wrote a fantastic article about the headaches that come with detecting screen width and height from JavaScript. Furthermore, not all mobile devices support window.onOrientationChange
and window.orientation
members (and those that do don't necessarily do so consistently either).
Because of this, I'm working on a snippet to detect orientation and polyfill if it's not supported. The issue that I have, though, is dealing with identifying when the orientation changes on multiple devices.
The below snippet works on small screens (e.g. Android and iPhones):
var newOrientation
, currentWidth = document.getElementsByTagName("body")[0].clientWidth;
// since there's bugs around devices supporting and reporting screen.width, using body instead
// set orientation
// TODO: Correct hard coded breakpoint.
if (window.hasOwnProperty("orientation")) { newOrientation = window.orientation; }
if (typeof newOrientation === "undefined") { newOrientation = (currentWidth > 400) ? 1 : 0; }
The code declares the
newOrientation
to test for the change against the currentOrientation variable (not shown).Because of issue with screen.width, I'm grabbing the body tag's clientWidth property as a benchmark (CSS has body.width set to 100%)
Next, I set
newOrientation
towindow.orientation
if the browser supports such.Finally, I check if
newOrientation
has been defined yet and if not, change it if the width is over a certain breakpoint (in this case, 400 which covers most phones).
I'm trying to find a better way to do point 4 since it doesn't scale well if I apply it to a Kindle Fire (600x1024) or an iPad2 (768x1024). One thing preventing me from comparing height to width is how long pages would skew this logic.
Does anyone have any suggestions how I might be able to modify this to compensate for larger screen widths?
Update After reviewing the linked article more and also taking into consideration GGG's suggestions, the code was refactored to the following:
var newWidth = window.outerWidth
, newOrientation = window.orientation || (newWidth !== currentWidth) ? 1 : 0;
if (newOrientation !== currentOrientation) {
currentOrientation = newOrientation;
currentWidth = newWidth;
}