Javascript android window.onorientationchange is constantly firing

I'm trying to detect orientation changes on mobile devices and run the function after the orientation is completed, but the code inside the function is constantly working in Android, and I'm not sure why. Here is 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 starts once, after the orientation change is completed?

+6
source share
3 answers

I used a workaround for this in my application. I added an event listener for changechange, and then set a timeout so that the orientation is exchanged, and I could get a new width value that actually reflects the width after changing the orientation.

 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'm not sure if this will solve your problem with continuous shooting, but this is the solution I found for work.

+8
source

I found a way to do this, if others still have the same problem, check this:

 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 } } 
+3
source

Simple solution for less detailed applications

 //bind orientation change event $(window).bind("orientationchange", orientationChange); //later, function orientationChange(){ //whatever needs to happen when it changes. alert("changed"); } 

Instead, you can use $ .on () if you need to pass information.

In browsers that do not support it, the event does not fire. You can then write your own discovery script as a backup to trigger the event if the orientation changes on a device that does not support onorientationchange.

0
source

Source: https://habr.com/ru/post/895702/


All Articles