Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript get mobile screen width after orientation change

I am capturing the orientationchange event like this:

            $(window).bind( 'orientationchange', function(e){

            });

How can I get the new screen width and height in pixels after the orientationchage?

I have tried screen.width but this doesn't change, it remains as the initial width, even after orientation change.

like image 856
ServerBloke Avatar asked Nov 02 '12 17:11

ServerBloke


4 Answers

$(window).bind( 'orientationchange', function(e){
    var ori = window.orientation,
        width = (ori==90 || ori==-90) ? screen.height : screen.width;
});
like image 168
Blazemonger Avatar answered Nov 20 '22 18:11

Blazemonger


Also you can use screen.availWidth. It gets changed with orientation.

like image 21
Sarim Avatar answered Nov 20 '22 20:11

Sarim


If you are using the meta tag viewport you could also update that tag (with jquery example:)

        function adapt_to_orientation() {
        var ori = window.orientation;
        var screenwidth = (ori==90 || ori==-90) ? screen.height : screen.width;
        var screenheight = (ori==90 || ori==-90) ? screen.width : screen.height;
                  // resize meta viewport
                  $('meta[name=viewport]').attr('content', 'initial-scale=1.0,maximum-scale=1.0,minimum-scale=1.0,user-scalable=no,width='+screenwidth + ',height=' + screenheight);
                }   
        adapt_to_orientation();
        $(window).bind( 'orientationchange', adapt_to_orientation);
like image 2
Air2 Avatar answered Nov 20 '22 18:11

Air2


Use $(window).resize, it runs after orientationchange

$(window).resize(function(){
        //your logic
});
like image 2
Alain Gauthier Avatar answered Nov 20 '22 19:11

Alain Gauthier