Forem

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.

Image of Timescale

๐Ÿš€ pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applicationsโ€”without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read more โ†’

Top comments (0)

Image of Docusign

๐Ÿ› ๏ธ Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more

๐Ÿ‘‹ Kindness is contagious

Explore a sea of insights with this enlightening post, highly esteemed within the nurturing DEV Community. Coders of all stripes are invited to participate and contribute to our shared knowledge.

Expressing gratitude with a simple "thank you" can make a big impact. Leave your thanks in the comments!

On DEV, exchanging ideas smooths our way and strengthens our community bonds. Found this useful? A quick note of thanks to the author can mean a lot.

Okay