Tony Edwards

One line device orientation detection – JavaScript

- 1 min

Following on from last weeks one line mobile detection method, here’s another useful one line method. This time, the method detects the devices orientation. I’m using this method to swap out images for each orientation.

var isPortrait = function() {
    return window.matchMedia("(orientation: portrait)").matches;
}

This method returns true if the device has an orientation of portrait. You can use this within a conditional statement like so:

if (isPortrait()){
    // Do some fancy upright stuff
}

Whilst this theoretically works in any browser that supports match media, there are some edge cases where unexpected results are returned.

If know any useful one line JS methods, let me know by dropping me a tweet.

rss twitter github youtube instagram linkedin medium stackoverflow tiktok facebook mastodon