11

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.

ServerBloke
  • 802
  • 3
  • 15
  • 24
  • Have you seen the recommendations [here](http://stackoverflow.com/questions/8508014/javascript-to-detect-mobile-browser-screen-width)? – barry Nov 02 '12 at 17:24

4 Answers4

12
$(window).bind( 'orientationchange', function(e){
    var ori = window.orientation,
        width = (ori==90 || ori==-90) ? screen.height : screen.width;
});
Walf
  • 8,535
  • 2
  • 44
  • 59
Blazemonger
  • 90,923
  • 26
  • 142
  • 180
  • I'm not sure that this would be any *faster*, but there's the option of: `width = Math.abs(window.orientation) == 90 ? screen.height : screen.width;` Which at least saves assigning a variable and a double-assessment of the same variable. (But a +1 for switching to a ternary between my first seeing the question -on mobile- and commenting.) – David Thomas Nov 02 '12 at 17:40
  • @DavidThomas It's a micro-optimization. The only reason I added the `ori` variable was to keep the line from being too long. – Blazemonger Nov 02 '12 at 17:43
5

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

Sarim
  • 3,124
  • 2
  • 20
  • 20
2

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);
Air2
  • 369
  • 3
  • 13
2

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

$(window).resize(function(){
        //your logic
});
Alain Gauthier
  • 820
  • 1
  • 12
  • 14
  • 1
    I voted this answer because previous answers are using previous widht and height ( the ones before rotation, i think the event is triggered right after the mobile is rotated while the window size (width) is still the same one). $(window).resize is triggered after the rotation is complete. – Drk_alien Jan 09 '18 at 11:15