Introduction to the Screen Orientation API in JavaScript

- Andrés Cruz

En español

Introduction to the Screen Orientation API in JavaScript

Example

When we are using a mobile device with Android and/or IOS (among other mobile operating systems), we will notice that when we rotate the device, the image projected on the screen "rotates" or adapts to the position in which the device is placed; in other words; the screen changes its orientation as the system detects that the device's viewing angle changed either in a horizontal (landscape) or vertical (portrait) position.

The Screen Orientation API in JavaScript is natively accessible through the JavaScript Screen object which provides the necessary primitives to detect the position of the device, lock and unlock specific positions; That is, use the same characteristics that applications have in mobile operating systems but we will have all this in a web application that with this we can better adapt to mobile using HTML.

In this entry we will see an introduction to this Screen Orientation API in JavaScript that can be essential when creating a web application so that it is correctly displayed on mobile devices since with this we can detect the orientation of the device and act accordingly; we will also see a small extra that allows us to show how to rotate the HTML content but with CSS.

Screen API properties and methods and events

As you have seen throughout this entry, the Screen orientation API extends the Screen object and has a couple of methods that complement each other:

1.0 The Screen.lockOrientation() method: To lock the screen

The screen.lockOrientation() method also accessible as window.screen.lockOrientation() allows you to lock (landscape and/or portrait) the screen given a specific orientation:

window.screen.lockOrientation(orientation);

The orientation parameter represents a specific orientation which can be:

  • portrait-primary This first screen orientation is in portrait mode and is the "normal" or "default" position of the device where the action buttons are in the background.
  • portrait-secondary This other orientation of the screen like the previous orientation is in portrait mode and is the "normal" or "default" position of the device but rotated 180 degrees where the action buttons are at the top.
  • landscape-primary This other orientation of the screen is in landscape mode and is the "normal" or "default" position of the device but rotated 90 degrees clockwise where the action buttons are on the right.
  • landscape-secondary Lastly, this screen orientation is in landscape mode and is the "normal" or "default" position of the device but rotated 270 degrees clockwise or 90 degrees counterclockwise where the action buttons are located on the left.

The orientation parameter is then used in the window.screen.lockOrientation(orientation) method through a String or String array to lock the screen according to the given orientations:

window.screen.lockOrientation('portrait'); window.screen.lockOrientation('portrait-primary', 'landscape-primary');

2.0 The Screen.unlock Orientation() method: To unlock the screen

If the first method we tried locked the screen based on the specified position, the Screen.unlockOrientation() method unlocks or releases the screen based on the screen orientation specified with the previous method.

The onorientationchange event

Finally, the Screen Orientation API also has an event that indicates when the screen has been rotated called onorientationchange, very useful when a device rotation occurs and the graphical interface must be updated.

Screen Orientation API Use Case

The experiment presented below was taken from: Introducing the Screen Orientation API where you can also find information regarding the Screen Orientation API; next we proceed to explain some code sections of the experiment:

The prefixes

Since JavaScript is native and not a framework like jQuery, it is necessary to verify browser support through prefixes. For this, the following lines of code are used:

            var prefix = 'orientation' in screen ? '' :
                    'mozOrientation' in screen ? 'moz' :
                    'webkitOrientation' in screen ? 'webkit' :
                    'msOrientation' in screen ? 'ms' :
                    NULL;

It may be the case that the browser simply does not support the Screen Orientation API, in which case a message such as "API not supported" will be displayed.

FullScreen Mode

To use the Screen Orientation API in JavaScript it is necessary that the page occupies the entire screen -full screen- therefore the full screen mode is activated and deactivated every time the selected device orientation is changed through the following functions respectively:

                function launchFullscreen(element) {
                    if (element.requestFullscreen) {
                        element.requestFullscreen();
                    }...
                }

                // desactiva el FullScreen
                function exitFullscreen() {
                    if (document.exitFullscreen) {
                        document.exitFullscreen();
                    }...
                }

Activate LockOrientation and unlockOrientation method

If the API is available, each time one of the buttons in the example is pressed, the screen will be unlocked/locked according to the selected mode:

                // bloquea la pantalla y activa el FullScreen
                document.getElementById('lock-button').addEventListener('click', function(event) {
                    event.preventDefault();
                    launchFullscreen(document.documentElement);

                    setTimeout(function() {
                        screen[prefix + (prefix === '' ? 'l' : 'L') + 'ockOrientation'](select.value);
                    }, 1);
                });

                // desbloquea la pantalla y desactiva el FullScreen
                document.getElementById('unlock-button').addEventListener('click', function() {
                    exitFullscreen();
                    screen[prefix + (prefix === '' ? 'u' : 'U') + 'nlockOrientation']();
                });

The event the LockOrientation and unlockOrientation method

A function is simply linked to the onorientationchange event that, remember, is activated every time the device is rotated:

                function orientationHandler() {
                    var orientationProperty = prefix + (prefix === '' ? 'o' : 'O') + 'rientation';
                    document.getElementById('orientation').textContent = screen[orientationProperty];
                }

                // activa el evento manejador
                screen.addEventListener(prefix + 'orientationchange', orientationHandler);

Example

Lock landscape/portrait with CCS

We are going to see a small plus or extra in which we show how we can rotate the HTML content of a website but this time using CSS to make everything even simpler; to do this, we present the following code that allows you to block the website in landscape and keep it as portrait:

#contenido { display:block; }

@media only screen and (orientation:portrait){
    #contenido {  
        -webkit-transform: rotate(90deg);
        -moz-transform: rotate(90deg);
        -o-transform: rotate(90deg);
        -ms-transform: rotate(90deg);
        transform: rotate(90deg);

    }
}

@media only screen and (orientation:landscape){

    #contenido {  
        -webkit-transform: rotate(0deg);
        -moz-transform: rotate(0deg);
        -o-transform: rotate(0deg);
        -ms-transform: rotate(0deg);
        transform: rotate(0deg);
    }
}
Andrés Cruz

Develop with Laravel, Django, Flask, CodeIgniter, HTML5, CSS3, MySQL, JavaScript, Vue, Android, iOS, Flutter

Andrés Cruz In Udemy

I agree to receive announcements of interest about this Blog.