Capture iPad orientation change

Sam Deering
Tweet

Code snippet to capture the change of orientation on your ipad device, you can then add very specific styles for each portrait and landsacape designs. The code adds a class to the html tag to assist with CSS (just like libraries such as Modernizr) using CSS3 media queries.

 
jQuery(document).ready(function($) {
 //capture ipad device change
function doOnOrientationChange()
{
    switch(window.orientation)
    {
      case -90: 
      case 90:
        alert('landscape'); //debug
        ////add class to assist with libraries like Modernizr
        $('html').removeClass('portrait').addClass('landscape'); 
        break;
      default:
        alert('portrait'); //debug
        $('html').removeClass('landscape').addClass('portrait');
        break;
    }
}

//setup event listener
window.addEventListener('orientationchange', doOnOrientationChange);

//initial call
doOnOrientationChange(); 
});

Example of CSS use.

 
/* styles for tablet only */
@media (min-width: 768px) and (max-width: 1024px)  {

    .portrait {

        /* styles for ipad landscape orientation */

    }    

    .landscape {

        /* styles for ipad landscape orientation */

    }
}

Get your free chapter of Level Up Your Web Apps with Go

Get a free chapter of Level Up Your Web Apps with Go, plus updates and exclusive offers from SitePoint.

No Reader comments