Search code examples
androidioscordovaorientationmedia-queries

iOS/Android Phonegap - portrait for smartphones, landscape on tablets


I'm creating a multidevice multiplatform app with Phonegap.

Basically, I have two scenarios:

  • Smartphones should be locked to portrait mode.
  • Tablets should be locked to landscape mode.

I should be able to customize the layout and placement with media queries, depending if the device is a tablet or smartphone (landscape or portrait, respectively). I've experimented with locking to portrait regardless of device, and then using CSS media queries and rotate transformations, but I run with two problems:

  • I haven't been able to find a media query that targets tablets and excludes smartphones and viceversa, the universe of resolutions seems to be too sparse.

  • Working with body{transform:rotate(90deg)} looks like a nightmare to nail everything down.

I also looked into: https://github.com/champierre/pg-plugin-screen-orientation but it seems to be working only for Android and I need to support both iOS and Android.

Does anyone have any experience with this particular scenario? Any suggestions on handling this orientation problem?


Solution

  • you can use navigator.userAgent to get the device type. For Example something like this:

    var deviceType = (navigator.userAgent.match(/iPad/i))  == "iPad" ? "iPad" : (navigator.userAgent.match(/iPhone/i))  == "iPhone" ? "iPhone" : (navigator.userAgent.match(/Android/i)) == "Android" ? "Android" : (navigator.userAgent.match(/BlackBerry/i)) == "BlackBerry" ? "BlackBerry" : "null";
    
    alert(navigator.userAgent);
    

    Or you can use the guide in this page...

    After that you can use the following code to set the orientation:

    $(window).bind('orientationchange', function(event){
    
        if (/*is tablet*/) {
         navigator.screenOrientation.set('landscape');
        } 
        else if (/* is smart phone */) {
         navigator.screenOrientation.set('portrait');
        }
    
       });
    

    I hope that above codes be helpful for you ;)