6

I have some code I wrote that alerts the user on mobile phones that change to landscape to basically go to portrait. This works great but if the user starts off in landscape it obviously doesnt show since there is no orientation change. Is there a way to just get the orientation of the get go?

$(window).on("orientationchange",function(){
        if( (window.orientation == 90 && $( window ).width() < 780) || (window.orientation == -90 && $( window ).width() < 780) ) // Landscape
        {
          $('body').append('<div class="phoneLandscape"><h4>Sorry, this site is best viewed in Portrait Mode</h4></div>');
        }
        else // Portrait
        {
          $('.phoneLandscape').remove();
        }
      });
Packy
  • 3,405
  • 9
  • 50
  • 87
  • possible duplicate of http://stackoverflow.com/questions/4917664/detect-viewport-orientation-if-orientation-is-portrait-display-alert-message-ad – Guillaume Beauvois Jun 11 '15 at 15:55

1 Answers1

12

jQuery mobile has the method $(window).on("orientationchange") but if you're looking to detect orientation at any given time try this

if(window.innerHeight > window.innerWidth){
    //portrait
}
if(window.innerWidth > window.innerHeight){
    //landscape
}
stackoverfloweth
  • 6,669
  • 5
  • 38
  • 69
  • 2
    But wouldn't this also affect non mobile devices? What if you only wanted this to apply to mobile devices? – Matt Dec 17 '20 at 03:56