-1

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

}
Tronald
  • 37
  • 9
  • What about doing it with css? [Media Queries](http://www.w3schools.com/css/css_rwd_mediaqueries.asp) – Qsprec Oct 26 '16 at 08:42
  • @Media Queries, you don't have to use css. javascript/jQuery is more than capable of doing this. – Jackson Oct 26 '16 at 10:12

1 Answers1

1

Something like this could help you:

// Listen for orientation changes
window.addEventListener("orientationchange", function() {
    // Announce the new orientation number
    //alert(screen.orientation);

  var orr = screen.orientation;

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

  ///portrait view///
 $('.ls-overlay').hide();


  } else if(orr =='-90'){

  ///landscap view///
  $('.ls-overlay').show();



  }

 } 
}, false);

The code above first adds an event listener and listens for the orientationchange and then on orientation change it will check to see if the users device is a mobile or a tablet and then if variable orr is 0, it will do the portrait view stuff and if its -90, it will do the landscape view stuff.

For more information on orientationchange you can read this:

Detect change in orientation using javascript

jQuery mobile orientationchange

Community
  • 1
  • 1
Jackson
  • 800
  • 16
  • 36