An event is sent when the user changes the orientation of iPhone. By handling this event in your web content, you can determine the current orientation of the device and make layout changes accordingly. For example, display a simple textual list in portrait orientation and add a column of icons in landscape orientation.
Similar to a resize event, a handler can be added to the <body> element in HTML as follows:
<body onorientationchange="updateOrientation();"> |
where updateOrientation() is a handler that you implement in JavaScript.
In addition, the window object has an orientation property set to one of the values in Table 7-1. For example, if the user starts with the iPhone in portrait orientation and then changes to landscape orientation by turning the iPhone to the right, the window’s orientation property is set to -90. If the user instead changes to landscape by turning the iPhone to the left, the window’s orientation property is set to 90.
Value | Description |
|---|---|
| Portrait orientation. This is the default value. |
| Landscape orientation with the screen turned clockwise. |
| Landscape orientation with the screen turned counterclockwise. |
| Portrait orientation with the screen turned upside down. This value is currently not supported on iPhone. |
Listing 7-3 adds an orientation handler to the body element and implements the updateOrientation() JavaScript method to display the current orientation on the screen. Specifically, when an orientationchange event occurs, the updateOrientation() method is invoked, which changes the string displayed by the division element in the body.
Listing 7-3 Displaying the orientation
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" |
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> |
<html xmlns="http://www.w3.org/1999/xhtml"> |
<head> |
<title>Orientation</title> |
<meta name = "viewport" content="width=320, user-scalable=0"/> |
<script type="text/javascript" language="javascript"> |
function updateOrientation() |
{ |
var displayStr = "Orientation : "; |
switch(window.orientation) |
{ |
case 0: |
displayStr += "Portrait"; |
break; |
case -90: |
displayStr += "Landscape (right, screen turned clockwise)"; |
break; |
case 90: |
displayStr += "Landscape (left, screen turned counterclockwise)"; |
break; |
case 180: |
displayStr += "Portrait (upside-down portrait)"; |
break; |
} |
document.getElementById("output").innerHTML = displayStr; |
} |
</script> |
</head> |
<body onorientationchange="updateOrientation();"> |
<div id="output"></div> |
</body> |
</html> |
Last updated: 2008-02-05