Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 543
bcholmes Avatar asked Dec 13 '12 19:12

bcholmes


People also ask

How can we detect the orientation of the screen?

Detecting Orientation Changes in Javascript Should you need to simply detect when a user changes orientation, you can use the following event listener: screen. orientation. addEventListener("change", function(e) { // Do something on change });

What is Javascript orientation?

The term screen orientation refers to whether a browser viewport is in landscape mode (that is, the width of the viewport is greater than its height), or else in portrait mode (the height of the viewport is greater than its width)

How can you tell portrait from landscape?

The main difference between landscape and portrait image orientation is that a landscape image is wider than it is taller while a portrait image is taller than it is wider. In other words, Landscape images are captured in a horizontal layout while portrait images are captured in a vertical layout.


1 Answers

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);
}​
like image 135
Patrick Gunderson Avatar answered Oct 10 '22 21:10

Patrick Gunderson