Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript android window.onorientationchange fires continuously

I'm trying to detect orientation changes on mobile devices and trigger a function once an orientation has been completed, but the code inside the function is continuously firing in Android and I'm not sure why. Here's my code:

var supportsOrientationChange = "onorientationchange" in window;
var orientationEvent = supportsOrientationChange ? "orientationchange" : "resize";

window.addEventListener(orientationEvent, 
   function() { alert ('orientation changed'); }, 
   false
);

Does anyone know how to write this so that it only triggers once, after orientation change has been completed?

like image 721
mheavers Avatar asked Aug 23 '11 18:08

mheavers


2 Answers

I used a work-around for this in my app. I added an event listener for orientationchange and then set a timeout so the orientationchange could occur and I could get a new width value that actually reflected the width after the orientation change.

var device_width = 0;
$(document).ready(function () {
    var oc_timer;
    $(window).bind('orientationchange', function () {
        clearTimeout(oc_timer);
        oc_timer = setTimeout(function () {
            device_width = $(window).width();
        }, 500);
    });
});

I am not positive this will solve your continuously firing function problem but this is a solution I found to work.

like image 120
Jasper Avatar answered Oct 13 '22 21:10

Jasper


I found a way to do this in case others are still having the same issue, check it out:

function onOrientationChange() {
    if (typeof(this.orientation) === "undefined"){
        if (window.orientation == -90 || window.orientation == 90) {
            this.orientation = "landscape";
        } else {
            this.orientation = "portrait";
        }
        // alert ("in 1");
        // you code here for change
    }

    if ((window.orientation == -90 || window.orientation == 90) && (this.orientation == "portrait")) {
        this.orientation = "landscape";
        // alert ("in 2");
        // you code here for change
    }

    if ((window.orientation == 0 || window.orientation == 180) && (this.orientation == "landscape")) {
        this.orientation = "portrait";
        // alert ("in 3");
        // you code here for change
    }
}   
like image 23
user1759671 Avatar answered Oct 13 '22 20:10

user1759671