4

How to change the mobile orientation of mobile screen on the click of button? Like portrait view to landscape view?

Aniket Sahrawat
  • 12,410
  • 3
  • 41
  • 67
Bharat Negi
  • 507
  • 4
  • 12

3 Answers3

5

You can use -webkit-transform(CSS) property to change the orientation:

if( /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) ) {
    $('body').css({
        "-webkit-transform": "rotate(90deg)"
    }); 
}
Aniket Sahrawat
  • 12,410
  • 3
  • 41
  • 67
1

First make the body full screen. You can do it by

document.body.requestFullscreen().then(res=>console.log(res).catch(err=>console.log(err);

Then rotate it by using

screen.orientation.lock('landscape').then(res=>console.log(res)).catch(err=>console.log(err))

Note : This will work only in mobile browser. If you don't know how to use console in android chrome then please read this article Here

Tushar Upadhyay
  • 101
  • 1
  • 4
1

I think rotation in mobile requires an event listener to handle screen.orientation.lock error.

The .main-app is a body tag class.

In your HTML code add a button like:

    <div id="lock-landscape-btn" class="hidden">Lock</div>
    <div id="unlock-orientation" class="hidden">unLock</div>

In your JS code/file add an EventListener like:

    function rotateScreen () {

        document.querySelector('#lock-landscape-btn').addEventListener('click', function () {

            if( /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) ) {

                if(document.querySelector(".main-app").requestFullscreen) {
                    document.querySelector(".main-app").requestFullscreen();
                }else if(document.querySelector(".main-app").webkitRequestFullScreen) {
                    document.querySelector(".main-app").webkitRequestFullScreen();
                }

                screen.orientation.lock("landscape-primary")
                    .then(function() {
                        console.log('landscape-primary');
                    })
                    .catch(function(error) {
                        console.log(error);
                    });
            }

        });

        document.querySelector("#unlock-orientation").addEventListener('click', function() {
            screen.orientation.unlock();
        });
    };
Malki Mohamed
  • 1,578
  • 2
  • 23
  • 40