Tronald Tronald - 1 month ago 11
iOS Question

On mobile, how can I display an overlay when the screen orientation is in landscape and remove it when in portrait?

I would like to display an overlay on mobile devices only that warns the user to switch to portrait mode whenever the orientation is in landscape and I want the overlay removed when an orientation of portrait is detected, without having to refresh the page. My code currently works, but only when the page is refreshed.

I've made a jsfiddle as an example, but the actual code is different (shown below), but I believe the concept is the same. Please resize the result window into landscape and hit run to see the overlay applied. My goal is to make the JS apply without having to hit run again or refresh the page.

JS FIDDLE EXAMPLE: https://jsfiddle.net/mrx7a0q5/

ACTUAL JS IM USING:

if (/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) && (window.innerWidth > window.innerHeight) == true) {

$('.ls-overlay').css("display", "block");
console.log("displaying");
} else {
$('.ls-overlay').css("display", "none");
console.log("not displaying");

}

Answer

you can use CSS with a styled div container instead, which will show when the device is in portrait mode.

You can catch the orientation with a media query

/* for all screens */
#info {display: none;}

/* only when orientation is in portrait mode */
@media all and (orientation:portrait) {
    #info {
         display: block;
    }
}