javascriptjquerymobileviewportdevice-orientation

Detect viewport orientation, if orientation is Portrait display alert message advising user of instructions


I am building a website specifically for mobile devices. There is one page in particular which is best viewed in landscape mode.

Is there a way to detect if the user visiting that page is viewing it in Portrait mode and if so, display a message informing the user that the page is best viewed in landscape mode? If the user is already viewing it in landscape mode then no message will appear.

So basically, I want the site to detect the viewport orientation, if orientation is Portrait, then display an alert message advising the user that this page is best viewed in Landscape mode.


Solution

  • if(window.innerHeight > window.innerWidth){
        alert("Please use Landscape!");
    }
    

    jQuery Mobile has an event that handles the change of this property... if you want to warn if someone rotates later - orientationchange

    Also, after some googling, check out window.orientation (which is I believe measured in degrees...)

    EDIT: On mobile devices, if you open a keyboard then the above may fail, so can use screen.availHeight and screen.availWidth, which gives proper height and width even after the keyboard is opened.

    if(screen.availHeight > screen.availWidth){
        alert("Please use Landscape!");
    }