2011/05/20

Detectando la rotación de pantalla en Android

Snippet para detectar cambios en la orientación de pantalla en dispositivos móviles. Está pensado para Android, pero supongo que serviría para cualquier plataforma móvil. Realmente no controla que se rote, si no que controla si existe el evento de "onorientationchange" y asigna una función a él. En el caso de que el evento no esté soportado, vincula el evento a resize.

// Detect whether device supports orientationchange event,
// otherwise fall back to the resize event.
var supportsOrientationChange = "onorientationchange" in window,
    orientationEvent = supportsOrientationChange ? "orientationchange" : "resize";

window.addEventListener(orientationEvent, function() {
    alert('HOLY ROTATING SCREENS BATMAN:' + window.orientation + " " + screen.width);
}, false);

Como guinda del pastel, en el caso de que se vincule al evento "resize", se podrían definir 2 variables globales (al contexto) llamadas por ejemplo "screenW" y "screenH" que se controlan en el evento de modo que si están intercambiadas, se ha cambiado la orientación. Con ello, nuestro código quedaría así.

var _screenW = screen.width;
var _screenH = screen.height;

// Detect whether device supports orientationchange event,
// otherwise fall back to the resize event.
var supportsOrientationChange = "onorientationchange" in window,
    orientationEvent = supportsOrientationChange ? "orientationchange" : "resize";

window.addEventListener(orientationEvent, function() {
    if(supportsOrientationChange ||
      (!supportsOrientationChange && _screenW == screen.height && _screenH == screen.width))
   {
       alert('HOLY ROTATING SCREENS BATMAN:' + window.orientation + " " + screen.width);
   }
}, false);

1 comentario:

  1. Información súper útil y funciona!!!!!!!!!!!!!!!!

    ResponderEliminar