DEV Community

Cover image for The Easiest Way to Detect Device Orientation in JavaScript
Dom (dcode)
Dom (dcode)

Posted on

The Easiest Way to Detect Device Orientation in JavaScript

In this post, we'll take a look at the easiest way to detect device orientation on the web with JavaScript.

This is compatible with all major browsers (including Safari) and works on mobile/tablet devices.

Video Tutorial

If you'd prefer to watch a video, you can find my 4 minute tutorial down below on YouTube:

OK, let me show you how easy this is.

Detect Portait/Landscape Mode with matchMedia()

We can use window.matchMedia(...) to detect if we are in portrait mode. The best part about this is that if you're not in portrait mode, you must be in landscape mode.

const portrait = window.matchMedia("(orientation: portrait)").matches;

// portrait = `true` or `false` 😮
Enter fullscreen mode Exit fullscreen mode

Using the above technique, we're able to detect if a user is in portrait mode at the current point in time.

But what if we want to react when a user changes their device orientation? This includes when they rotate their mobile device.

This is easily done by using addEventListener.

window.matchMedia("(orientation: portrait)").addEventListener("change", e => {
    const portrait = e.matches;

    if (portrait) {
        // do something
    } else {
        // do something else
    }
});
Enter fullscreen mode Exit fullscreen mode

And that's it! Very easy to do 😎

Enrol Now 👉 JavaScript DOM Crash Course

If you're learning web development, you can find a complete course on the JavaScript DOM at the link below 👇
https://www.udemy.com/course/the-ultimate-javascript-dom-crash-course/?referralCode=DC343E5C8ED163F337E1

Course Thumbnail

Enjoy.

Top comments (0)