Capture iPad orientation change

Sam Deering

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

    }
}

Win an Annual Membership to Learnable,

SitePoint's Learning Platform

No Reader comments

Comments on this post are closed.