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 */

    }
}

Free book: Jump Start HTML5 Basics

Grab a free copy of one our latest ebooks! Packed with hints and tips on HTML5's most powerful new features.

No Reader comments