bcholmes
bcholmes

Reputation: 974

JavaScript algorithm to determine orientation of tablet

We're building an HTML5/JavaScript app developed for tablets, and we want to lay out my screens differently in landscape versus portrait.

Originally, we were capturing orientation change notifications, and keeping track of the current orientation (generally reported as 0, 90, -90 or 180 degrees -- see this question). Unfortunately, different devices report different orientations as "0". That link argues that it's a bug, but there's some evidence that this is working-as-designed -- for example, this article suggests that "landscape" is the default orientation and those devices report an orientation of "0" when held in landscape mode.

We next tried to just look at the actual screen size, assuming that when width was greater than height, we were in landscape mode. But this algorithm gets confused when the on-screen keyboard is displayed -- when the keyboard is displayed, the dimensions of the visible area are returned. When the device is, strictly speaking, in portrait mode, but the portion of the screen not obscured by the keyboard is wider than it is tall.

The response to this question is quite old. Is that still the best answer? Does anyone have a good algorithm that takes the keyboard visibility into consideration?

Upvotes: 8

Views: 2464

Answers (1)

Patrick Gunderson
Patrick Gunderson

Reputation: 3281

http://jsfiddle.net/jjc39/

Try this:

<span id="orientation">orientation</span>​

$(document).ready(checkOrientation);
$(window).resize(checkOrientation);

function checkOrientation() {
    var orientation = "Portrait";
    var screenWidth = $(window).width();
    var screenHeight = $(window).height();
    if (screenWidth > screenHeight) {
        orientation = "Landscape";
    }
    $("#orientation").html(orientation);
}​

Upvotes: 4

Related Questions