Snippets

Add iPhone/iPad Orientation to Body Class

This function will detect the orientation (portrait/landscape) of an iOS device and set the body class to either portrait or landscape, as well as providing a global variable for use elsewhere in your JS.

If you require multiple classes on your body tag, simply alter the code to use jQuery’s addClass() and removeClass() functions.

function orient() {
    if (window.orientation == 0 || window.orientation == 180) {
        $("body").attr("class", "portrait");
        orientation = 'portrait';
     
        return false;
    }
    else if (window.orientation == 90 || window.orientation == -90) {
        $("body").attr("class", "landscape");
        orientation = 'landscape';
     
        return false;
    }
}
     
/* Call orientation function on page load */
$(function(){
    orient();
});
     
/* Call orientation function on orientation change */
$(window).bind( 'orientationchange', function(e){
    orient();
});

Share this snippet

 

Comments (1) - Leave yours

Leave a Reply

Your email address will not be published. Required fields are marked *

Please respect the following rules: No advertising, no spam, no keyword in name field. Thank you!