jquery detect phone orientation
Asked Answered
O

3

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();
        }
      });
Octangular answered 11/6, 2015 at 15:51 Comment(1)
possible duplicate of #4918164Fodder
L
13

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
}
Latecomer answered 11/6, 2015 at 15:54 Comment(1)
But wouldn't this also affect non mobile devices? What if you only wanted this to apply to mobile devices?Fractocumulus
I
-1

you can put it inside this:

if( /Android|webOS|iPhone|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) ) {
    
 if(window.innerHeight > window.innerWidth){
  //portrait
 }

 if(window.innerWidth > window.innerHeight){
  //landscape
}

}
Ignatz answered 8/9 at 8:49 Comment(0)
G
-1

Landscape is the state when height is greater than width and portrait is the state when width is greater than height. So you can implement this logic as a method that I named getOrientation() and even implement stuff like isLandscape and isPortrait using it. And of course you can call it anytime, including page load.

function getOrientation() {
    const w = $( window );
    return (w.width() > w.height()) ? "landscape" : "portrait";
}

function isLandscape() {
    return getOrientation() === "landscape";
}

function isPortrait() {
    return getOrientation() === "portrait";
}

console.log("Is landscape: " + isLandscape());
console.log("Is portrait: " + isPortrait());
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
Glenine answered 11/9 at 11:5 Comment(1)
This answer was down-voted. I would appreciate a comment, so I would edit it accordingly, or, if it is very bad, remove it. Thanks!Glenine

© 2022 - 2024 — McMap. All rights reserved.