19

I'm trying to figure out how to change an embedded web page when the user rotates their phone from portrait to landscape mode - basically to load a view that is better suited to the wider screen format. Is this possible to do without calling a new page from the server, i.e. to drive it from within CSS/Javascript itself?

Thanks!

tbacos
  • 733
  • 2
  • 7
  • 12

6 Answers6

19

You can use the window.orientation property. Its value is the degree that the current mode of view is used. Here is a brief example:

function updateOrientation()
{   
    var orientation=window.orientation;
    switch(orientation)
    {

        case 0:

                break;  

        case 90:
                break;

        case -90:   

                break;
    }

}

You can use this function on this event:

window.onorientationchange=updateOrientation;

Hope that helps!

alex
  • 479,566
  • 201
  • 878
  • 984
anthares
  • 11,070
  • 4
  • 41
  • 61
7

Best not to set the onorientationchange property directly. Instead use the following:

window.addEventListener('orientationchange', function (evt) {
    switch(window.orientation) {
        case 0: // portrait
        case 180: // portrait
        case 90: // landscape
        case -90: // landscape
    }
}, false);
Andrew Hedges
  • 21,688
  • 16
  • 67
  • 79
5

The Safari mobile browser has support for the orientationchange event as well as the orientation property on the window, so you can do something like:

window.onorientationchange = function() {
    switch(window.orientation) {
        case 0:   // Portrait
        case 180: // Upside-down Portrait
            // Javascript to setup Portrait view
            break;
        case -90: // Landscape: turned 90 degrees counter-clockwise
        case 90:  // Landscape: turned 90 degrees clockwise
            // Javascript to steup Landscape view
            break;
    }
}

I would add the upside-down because the iPad human interface guidelines say you should support all orientations, so I would expect Safari on the iPad (and possibly future iPhone versions) to support it.

Cœur
  • 37,241
  • 25
  • 195
  • 267
Ben S
  • 68,394
  • 30
  • 171
  • 212
5

I can't believe no one talked about the css ruling:

@media screen and (max-width: 320px) // Portait Mode
{
/* CSS RULINGS */
p{}
body{}
}

@media screen and (min-width: 321px) // Landscape Mode
{
/* CSS RULINGS */
p{}
body{}
}
Itai Sagi
  • 5,537
  • 12
  • 49
  • 73
0

Safari Mobile supports orientation events.

Giao
  • 14,725
  • 2
  • 24
  • 18
0
<body onorientationchange="updateOrientation();">

From: Safari Web Content Guide

jessecurry
  • 22,068
  • 8
  • 52
  • 44