33

How to detect with or when user turns iPad from vertical position to horizontal or from horizontal to vertical?

Community
  • 1
  • 1
lolalola
  • 3,773
  • 20
  • 60
  • 96

4 Answers4

42

Try

$(window).bind('orientationchange', function(event) {
  alert('new orientation:' + event.orientation);
});
Karl-Bjørnar Øie
  • 5,554
  • 1
  • 24
  • 30
  • 5
    On the Ipad 1 I'm testing with the event object does not have an orientation property, but the window object does, so I had to use `orientation` rather than `event.orientation`. – tremby Oct 02 '12 at 23:15
  • Thank you very much for the answer @Karl-Bjørnar Øie.It solved my issue in the best way! – Anahit Ghazaryan Jun 03 '15 at 07:57
  • @Mrunal in pageLoad() or similar function that will always be called before the page will actually be interacted with. – GreySage Jul 20 '17 at 17:24
20

You can detect the orientation change event using the following code:

jQuery:

$(document).ready(function() {
    $(window).on('orientationchange', function(event) {
        console.log(orientation);
    });
});

Check if device is in portrait mode

function isPortrait() {
    return window.innerHeight > window.innerWidth;
}
martynas
  • 12,120
  • 3
  • 55
  • 60
12

In Javascript:

<button onclick="detectIPadOrientation();">What's my Orientation?</button>

<script type="text/javascript">
 window.onorientationchange = detectIPadOrientation;
 function detectIPadOrientation () {

    if ( orientation == 0 ) {
     alert ('Portrait Mode, Home Button bottom');
    }
    else if ( orientation == 90 ) {
     alert ('Landscape Mode, Home Button right');
    }
    else if ( orientation == -90 ) {
     alert ('Landscape Mode, Home Button left');
    }
    else if ( orientation == 180 ) {
     alert ('Portrait Mode, Home Button top');
    }
 }
</script>

Or for including additional stylesheets:

<link rel="stylesheet" media="all and (orientation:portrait)" href="portrait.css">
<link rel="stylesheet" media="all and (orientation:landscape)" href="landscape.css">

Both taken from: http://favo.asia/2010/07/detecting-ipad-orientation-using-javascript/ which, FYI, was the first result on Google for 'detect ipad orientation javascript'...

Simon
  • 37,815
  • 2
  • 34
  • 27
-1
function detectIPadOrientation (orientation) {  
   if ( orientation == 0 ) {  
    alert ('Portrait Mode, Home Button bottom');  
   }  
   else if ( orientation == 90 ) {  
    alert ('Landscape Mode, Home Button right');  
   }  
   else if ( orientation == -90 ) {  
    alert ('Landscape Mode, Home Button left');  
   }  
   else if ( orientation == 180 ) {  
    alert ('Portrait Mode, Home Button top');  
   }  
}

window.onorientationchange = detectIPadOrientation;

Fatih Acet
  • 28,690
  • 9
  • 51
  • 58