Detecting Device Orientation with Javascript
📣 Sponsor
Sometimes, you just want to know if a screen is in portrait or landscape mode. There are two primary places you would want to do this: in Javascript, and in CSS. Let's look at how to detect the screen's orientation in both.
Detecting Orientation in CSS
In CSS, simply 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 simply 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. If you need to, you can use the matchMedia
query from above to achieve similar functionality.
Conclusion
Detecting screen orientation is easy - and in the future we'll be able to use screen.orientation
to reliably do this. For now, it's best to stick with CSS media queries and window.matchMedia
.
More Tips and Tricks for Javascript
- Making a Morphing 3D Sphere in Javascript with Three.js
- Truthy and Falsy Values in Javascript
- Checking if a value is a number in Javascript with isNaN()
- Making your own Email Subscription Service with Node.JS
- The Free Course for Javascript
- A Guide to Heaps, Stacks, References and Values in Javascript
- Javascript Ordinals: Adding st, nd, rd and th suffixes to a number
- Javascript Logical Statements and Loops
- How to Check if Object is Empty in JavaScript
- Javascript Proxy: Using Javascript Proxies like a Pro