javascript – Detect mobile screen orientation on devices with static screen dimensions, regardless of screen orientation


I’m currently building a portfolio website which would benefit from changing site layout to either a one column or two column design depending on the orientation of the screen for mobile browsers. I initially tried using @media (orientation:portrait) and @media (orientation:landscape), but found that my Galaxy Note 8 would only ever trigger the landscape mode, even when the phone is in portrait orientation. I then brute forced a JS solution like so:

        <link rel="stylesheet" type="text/css" href="mobileportrait.css" id="portrait" />
        <link rel="stylesheet" type="text/css" href="mobilelandscape.css" id="landscape" />
        <script type="text/javascript">
            if (screen.height <= screen.width) {
                document.getElementById('landscape').disabled = false;
                document.getElementById('portrait').disabled = true;
            }
            else {
                document.getElementById('landscape').disabled = true;
                document.getElementById('portrait').disabled = false;
            }
            window.addEventListener('resize', function(event){
                if (screen.height <= screen.width) {
                document.getElementById('landscape').disabled = false;
                document.getElementById('portrait').disabled = true;
                }
                else {
                    document.getElementById('landscape').disabled = true;
                    document.getElementById('portrait').disabled = false;
                } 
            });
        </script>

But even this only loads the landscape stylesheet on all the phones I tried it with. This leads me to believe that the modern mobile phones I’m targeting report the longest side as screen width and the shortest side as screen height regardless of the actual orientation of the screen, which causes CSS orientation and JS screen.height <= screen.width to both fail miserably.

My question is simple, how does one go about detecting the orientation of a mobile phone that acts in this manner?



Source link

Latest articles

Related articles

Leave a reply

Please enter your comment!
Please enter your name here