4

What is the best approach to change a css file when a mobile application page orientation changes from landscape to portrait and vice versa. I need to suport both Android and iPhone only. It seems media queries aren't the cleanest way, any other ideas?

c12
  • 9,557
  • 48
  • 157
  • 253
  • Isn't there any option to bind to window resize event, and if X is bigger then Y it is landscape? And Y bigger then X you got portrait? Keep 1 var as a boolean, isLandscape and if it's changed, edit your stylesheet? – Niels Nov 11 '11 at 23:35
  • 1
    Why you think that CSS media queries aren't clean solution? – Wojciech Bednarski Nov 11 '11 at 23:47

4 Answers4

7

Example

/* For portrait */
@media screen and (orientation: portrait) {
  #toolbar {
    width: 100%;
  }
}

/* For landscape */

@media screen and (orientation: landscape) {
  #toolbar {
    position: fixed;
    width: 2.65em;
    height: 100%;
  }

  p {
    margin-left: 2em;
  }
}

For more details see here

isxaker
  • 8,446
  • 12
  • 60
  • 87
1

First give your style sheet include line an id="cssElement" or something.

Then Using jQuery:

$(document).ready(function(){   

   // The event for orientation change
   var onChanged = function() {

      // The orientation
      var orientation = window.orientation;

      if(orientation == 90) { 
          $('#cssElement').attr('href', '/path/to/landscape.css');
      } else {
          $('#cssElement').attr('href', '/path/to/portrait.css');
      }

   };

   // Bind the orientation change event and bind onLoad
   $(window).bind(orientationEvent, onChanged).bind('load', onChanged);

});
Rick Kukiela
  • 1,135
  • 1
  • 15
  • 34
1

The below JQuery code seems to work best for me...the binding examples did not.

$(document).ready(function() {
               $(window).resize(function() {
                  alert(window.orientation);
                  });
               });
c12
  • 9,557
  • 48
  • 157
  • 253
0

You can use window.onorientationchange event.

Wojciech Bednarski
  • 6,033
  • 9
  • 49
  • 73