Tronald Tronald - 1 year ago 58
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.



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

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


Answer Source

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;

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download