Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
September 13, 2022 02:06 pm GMT

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` 

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    }});

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.


Original Link: https://dev.to/dcodeyt/the-easiest-way-to-detect-device-orientation-in-javascript-7d7

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To