benhowdle89
benhowdle89

Reputation: 37504

Detect Phone orientation on load

Is this possible to check with Javascript on page load. I know you can detect a change in orientation but is it possible to check what state the phone is in straight away?

Thanks

Upvotes: 1

Views: 2669

Answers (2)

Pantelis
Pantelis

Reputation: 6146

You can do this...

 var currOrientation= '';
/************************
* Changes the (obj) element's class, to 
* -vrt (vertical)
* -hrz (horizontal)
* depending on its width
*************************/
var orientation = function( obj ){
    var w = getWidth(),
        h = getHeight();

    if( w <= h && currOrientation !== 'vrt' ){
        obj.className = 'vrt';
        currOrientation = 'vrt';
    }
    else if( currOrientation !== 'hrz' ) {
        obj.className = 'hrz';
        currOrientation = 'hrz';
    }
}
/************************
* Binding a repeating timer
************************/
var orientationINIT = function() {
    var content;
    if( (content = document.getElementsByTagName('body')[0]) != undefined ){
        orientation( content );

        var Orient = setInterval( function() {
            orientation( content );
        }, 500 ); //each 500ms a call for orientation change
    }
}

orientationINIT should be called on page load or DOM complete (or at the bottom of the page )

where getHeight() and getWidth() should be simple functions that return the window's width / height in number form.

Upvotes: 1

Jens Roland
Jens Roland

Reputation: 27770

You could check the viewport width and height and see which one is larger:

var isLandscapeMode = window.innerWidth > window.innerHeight;

if (isLandscapeMode) {
  // fit page to wide orientation here...
}

For a more in-depth discussion of viewport sizes on mobile devices, see http://www.quirksmode.org/mobile/viewports2.html

(Updated code)

Upvotes: 3

Related Questions