Javascript screen orientation on safari

El arquitecto picture El arquitecto · Jun 22, 2017 · Viewed 12.4k times · Source

I'm trying to make a responsive web site and it is almost finished, but I need a hand.

I'm using this example to know the angle:

    angulo = screen.orientation || screen.mozOrientation || screen.msOrientation;
    
    Example angulo.angle

It returns 0, but it does not work with Safari, only with MSF and Chrome. In Safari it shows:

TypeError: undefined is not an object (evaluating 'angulo.angle')

What can I do?

Answer

Rachel Gallen picture Rachel Gallen · Jun 22, 2017

If it's a case that you need the angle to determine whether your page is in portrait or landscape mode, then use the following:

document.addEventListener("orientationchange", updateOrientation);

You could also use matchMedia

var mql = window.matchMedia("(orientation: portrait)");

// If there are matches, we're in portrait
if(mql.matches) {  
    // Portrait orientation
} else {  
    // Landscape orientation
}

// Add a media query change listener
mql.addListener(function(m) {
    if(m.matches) {
        // Changed to portrait
    }
    else {
        // Changed to landscape
    }
});

OR you could use a resize event

window.addEventListener("resize", function() {
    // Get screen size (inner/outerWidth, inner/outerHeight)

}, false);

There are more hints in David Walsh's handy article (but probably other examples too on SO)