d

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore.

15 St Margarets, NY 10033
(+381) 11 123 4567
ouroffice@aware.com

 

KMF

Detecting Screen Orientation in JavaScript

Sometimes, you want to know if a screen is in portrait or landscape mode. There are two primary places you would like to do this: JavaScript and CSS. So let’s look at how to detect the screen’s orientation in both.

Detecting Orientation in CSS

In CSS, use the following media queries to match any portrait or landscape device:

/* Portrait orientation */
@media screen and (orientation: portrait) {

}
/* Landscape orientation */
@media screen and (orientation: landscape) {

}

Detecting Orientation in JavaScript

Since screen.orientation has patchy support; you can use the same media query in JavaScript like so:

let portrait = window.matchMedia("(orientation: portrait)");

portrait.addEventListener("change", function(e) {
    if(e.matches) {
        // Portrait mode
    } else {
        // Landscape
    }
})

Detecting Orientation Changes in JavaScript

Should you need to detect when a user changes orientation, you can use the following event listener:

screen.orientation.addEventListener("change", function(e) {
    // Do something on change
});

Currently, this is not supported in Safari, so your mileage may vary on this one. However, you can use the matchMedia query from above to achieve similar functionality if you need to.

Conclusion

Detecting screen orientation is easy – and in the future, we’ll be able to use screen.orientation to do this reliably. For now, it’s best to stick with CSS media queries and window.matchMedia.

Credit: Source link

Previous Next
Close
Test Caption
Test Description goes like this