DEV Community

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

Posted on

23

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.

Tiugo image

Modular, Fast, and Built for Developers

CKEditor 5 gives you full control over your editing experience. A modular architecture means you get high performance, fewer re-renders and a setup that scales with your needs.

Start now

Top comments (0)

Neon image

Next.js applications: Set up a Neon project in seconds

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Get started โ†’

๐Ÿ‘‹ Kindness is contagious

Engage with a wealth of insights in this thoughtful article, valued within the supportive DEV Community. Coders of every background are welcome to join in and add to our collective wisdom.

A sincere "thank you" often brightens someoneโ€™s day. Share your gratitude in the comments below!

On DEV, the act of sharing knowledge eases our journey and fortifies our community ties. Found value in this? A quick thank you to the author can make a significant impact.

Okay