Orientation Event for iPhone webapplications

By

March 29, 2012Scripts2 Comments

iphone orientation 300x157 Orientation Event for iPhone webapplications

iphone-orientation

It is right time to share one of nice article with you freinds….

Recently i started working on making websites for mobiles(iPhone). I had a great experience with it. I come across with the image orientation issue with banner in home page. I have done some research on it. Finally i could get the solution for it.

My requirement is that: I need to apply the class dynamically based on the mobile orientation. If mobile is oriented in portrait mode then the widh of banner should be 320px and apply some styles. In other case, If mobile is oriented in landscape mode then the widht of banner should be 480px and apply some styles.


Above requirement can be achieved with the following code:

<html>
<head>
  <title>iphone test page</title>
  <style type="text/css">
  .portrait{
    background:#fff url("images/banner-12-320.png") no-repeat center;
    height:200px;
    width:320px;
    display:block;
  }
  .landscape{
    background:#fff url("images/banner-12-490.png") no-repeat center;
    height:200px;
    width:480px;
    display:block;
  } 
  </style>
</head>
<body>
<script type="text/javascript">           
  function doActionOnOrientation()
  {
    switch(window.orientation) 
    {  
      case -90:
      case 90:
	//alert('landscape');
	document.getElementById("banner_img").setAttribute("class", "landscape");
        break; 
      default:
        //alert('portrait');
	document.getElementById("banner_img").setAttribute("class", "portrait");
        break; 
    }
  }
 
  window.onorientationchange = function()
  {
    doActionOnOrientation();
  };
 
  // Initial execution
  doActionOnOrientation();
</script>
<div id="banner_img" class="portrait"></div>
</body>
</html>