How do I correctly detect orientation change using Phonegap on iOS?
Solution 1
This is what I do:
function doOnOrientationChange() {
switch(window.orientation) {
case -90: case 90:
alert('landscape');
break;
default:
alert('portrait');
break;
}
}
window.addEventListener('orientationchange', doOnOrientationChange);
// Initial execution if needed
doOnOrientationChange();
Update May 2019: window.orientation
is a deprecated feature and not supported by most browsers according to MDN. The orientationchange
event is associated with window.orientation and therefore should probably not be used.
Solution 2
I use window.onresize = function(){ checkOrientation(); }
And in checkOrientation you can employ window.orientation or body width checking
but the idea is, the "window.onresize" is the most cross browser method, at least with the majority of the mobile and desktop browsers that I've had an opportunity to test with.
Solution 3
if (window.matchMedia("(orientation: portrait)").matches) {
// you're in PORTRAIT mode
}
if (window.matchMedia("(orientation: landscape)").matches) {
// you're in LANDSCAPE mode
}
Solution 4
I'm pretty new to iOS and Phonegap as well, but I was able to do this by adding in an eventListener. I did the same thing (using the example you reference), and couldn't get it to work. But this seemed to do the trick:
// Event listener to determine change (horizontal/portrait)
window.addEventListener("orientationchange", updateOrientation);
function updateOrientation(e) {
switch (e.orientation)
{
case 0:
// Do your thing
break;
case -90:
// Do your thing
break;
case 90:
// Do your thing
break;
default:
break;
}
}
You may have some luck searching the PhoneGap Google Group for the term "orientation".
One example I read about as an example on how to detect orientation was Pie Guy: (game, js file). It's similar to the code you've posted, but like you... I couldn't get it to work.
One caveat: the eventListener worked for me, but I'm not sure if this is an overly intensive approach. So far it's been the only way that's worked for me, but I don't know if there are better, more streamlined ways.
UPDATE fixed the code above, it works now
Solution 5
Although the question refers to only PhoneGap and iOS usage, and although it was already answered, I can add a few points to the broader question of detecting screen orientation with JS in 2019:
window.orientation
property is deprecated and not supported by Android browsers.There is a newer property that provides more information about the orientation -screen.orientation
. But it is still experimental and not supported by iOS Safari. So to achieve the best result you probably need to use the combination of the two:const angle = screen.orientation ? screen.orientation.angle : window.orientation
.As @benallansmith mentioned in his comment,
window.onorientationchange
event is fired beforewindow.onresize
, so you won't get the actual dimensions of the screen unless you add some delay after the orientationchange event.There is a Cordova Screen Orientation Plugin for supporting older mobile browsers, but I believe there is no need in using it nowadays.
There was also a
screen.onorientationchange
event, but it is deprecated and should not be used. Added just for completeness of the answer.
In my use-case, I didn't care much about the actual orientation, but rather about the actual width and height of the window, which obviously changes with orientation. So I used resize
event to avoid dealing with delays between orientationchange
event and actualizing window dimensions:
window.addEventListener('resize', () => {
console.log(`Actual dimensions: ${window.innerWidth}x${window.innerHeight}`);
console.log(`Actual orientation: ${screen.orientation ? screen.orientation.angle : window.orientation}`);
});
Note 1: I used EcmaScript 6 syntax here, make sure to compile it to ES5 if needed.
Note 2: window.onresize
event is also fired when virtual keyboard is toggled, not only when orientation changes.
Related videos on Youtube
ajpalma
Updated on November 22, 2020Comments
-
ajpalma over 3 years
I found this orientation test code below looking for JQTouch reference material. This works correctly in the iOS simulator on mobile Safari but doesn’t get handled correctly in Phonegap. My project is running into the same issue that is killing this test page. Is there a way to sense the orientation change using JavaScript in Phonegap?
window.onorientationchange = function() { /*window.orientation returns a value that indicates whether iPhone is in portrait mode, landscape mode with the screen turned to the left, or landscape mode with the screen turned to the right. */ var orientation = window.orientation; switch (orientation) { case 0: /* If in portrait mode, sets the body's class attribute to portrait. Consequently, all style definitions matching the body[class="portrait"] declaration in the iPhoneOrientation.css file will be selected and used to style "Handling iPhone or iPod touch Orientation Events". */ document.body.setAttribute("class", "portrait"); /* Add a descriptive message on "Handling iPhone or iPod touch Orientation Events" */ document.getElementById("currentOrientation").innerHTML = "Now in portrait orientation (Home button on the bottom)."; break; case 90: /* If in landscape mode with the screen turned to the left, sets the body's class attribute to landscapeLeft. In this case, all style definitions matching the body[class="landscapeLeft"] declaration in the iPhoneOrientation.css file will be selected and used to style "Handling iPhone or iPod touch Orientation Events". */ document.body.setAttribute("class", "landscape"); document.getElementById("currentOrientation").innerHTML = "Now in landscape orientation and turned to the left (Home button to the right)."; break; case -90: /* If in landscape mode with the screen turned to the right, sets the body's class attribute to landscapeRight. Here, all style definitions matching the body[class="landscapeRight"] declaration in the iPhoneOrientation.css file will be selected and used to style "Handling iPhone or iPod touch Orientation Events". */ document.body.setAttribute("class", "landscape"); document.getElementById("currentOrientation").innerHTML = "Now in landscape orientation and turned to the right (Home button to the left)."; break; } }
-
Fresheyeball over 12 yearsHard coding the device to 320 or 480 will not work in the future, or with current hi-res phones.
-
Atadj about 12 yearsThat's the only solution that works for me from this discussion :) +1
-
Kirk Strobeck about 12 yearsI did
window.onorientationchange = function() { setTimeout(functionName, 0); };
-
backdesk about 12 yearsOut of interest, why did you use setTimeout Kirk?
-
CWSpear over 11 years@Crungmungus It's a hacky way to defer execution. It makes it do it last to ensure it's not getting the orientation before it actually rotates. I am not sure it's necessary, though (i.e.
window.orientation
should return the new orientation and not what orientation it was at). -
Dan over 11 years1) You should use
onresize
event that will fire immediately, not in 500 miliseconds 2) This code is android-specific, useonorientationchange
instead for iPhone 3) Test if it's supported in the browser:"onorientationchange" in window
-
Dan over 11 years@Kirk, what about your battery usage now? :)
-
Matt Ray over 10 yearsThis is a great point. If you are developing using a web-facing technology, this method allows you to debug and test more easily in a browser instead of deploying/simulating each time.
-
Dzhuneyt over 10 yearsNote that you can use 180 and 0 as values to get the portrait mode using the same method (in case you want portrait mode explicitly).
-
HellBaby about 10 yearsThis isn't ok at all...cause when the keyboard appears it will resize(and this isn't the only case). So a big no for this!
-
hndcrftd about 10 years@HellBaby When the keyboard appears the function will get called, however, depending on what method you use for orientation detection, it will detect that the orientation HAS NOT CHANGED, as would be the case with window.orientation. So I still stand by my answer.
-
HellBaby about 10 years@Raine I used that method on a Ipad 4 and was forced to change it cause of that issue. So maybe it's working for some devices but not for all..
-
hndcrftd about 10 years@HellBaby So, are you saying that window.orientation returned a conflicting value when the keyboard showed up on the iPad 4 screen? If that is the case, that behavior should be reported as a bug, and your code should be adjusted to account for that specific buggy behavior on that specific platform. I would be interested in finding out what other solution works for iPad 4 if window.orientation is unreliable.
-
Garavani almost 10 yearsI found this helpful, too: function readDeviceOrientation() { if (Math.abs(window.orientation) === 90) { // Landscape } else { // Portrait } } (williammalone.com/articles/html5-javascript-ios-orientation)
-
kontur almost 10 years@MattRay You can easily test orientation changes with latest dev toolkits that are capable of emulating this sort of device behavior.
-
Rituraj ratan almost 10 yearsthere is very good explanation tech-blog.maddyzone.com/javascript/detect-orientation-event
-
benallansmith over 8 yearsBe careful! This is device specific - the degrees refer to the difference from the devices standard orientation. In other words, if the tablet is designed to used in landscape, then 90 would mean it's in portrait mode. As a work around to this, I initially check the height vs width of the window to store the orientation, and use orientationchange to update this if there's a change.
-
benallansmith over 8 yearsAdditionally, I've found that the orientationchange fires before the width and height are changed, therefore a little bit of delay is needed in order to detect the orientation correctly using the width and height. For this, I store the current orientation, and when a change is detected, I check for the change in orientation in 50ms increments upto 250ms. Once a difference is found, I then update the page accordingly.On my Nexus 5, it usually detects the width vs height difference after 150ms.
-
WebWanderer over 8 yearsI would suggest altering your switch statement as
case 0: alert('Portrait'); break; default: alert('Landscape'); break;
-
Shaun Neal over 8 yearsdefinitely buggy on ios8 with safari - sometimes works sometimes not - trying to get a canvas to go full screen after orientation change - width and height values from window are all over the map and alot of delays
-
lowtechsun about 8 yearsI have had no problems with this cross device and cross browser solution for portrait and landscape detection.
$(window).bind("resize", function(){ screenOrientation = ($(window).width() > $(window).height())? 90 : 0; });
-
THE JOATMON almost 7 yearsBinding
resize
instead oforientationchange
allowed me to get rid of mysetTimeout
. Much better! -
GreySage almost 7 yearswindow.onresize() does not get fired for an ipad air when the orientation changes.
-
Alex W almost 7 yearsThe
||
operator shouldn't be used inswitch
statements unless you are wrapping the whole expression in parentheses. Otherwise, you will not get the behavior you expect. -
Sebastian Simon about 6 years
||
doesn’t work like this inswitch
.-90 || 90
is equivalent to just-90
. You actually need to usecase -90: case 90:
. -
N.K almost 6 yearsWhat if the device was already in portrait mode , how can i check ?
-
oldboy about 5 yearsaccording to mdn, this is not supported by chrome, edge, firefox, internet explorer, opera, and safari
-
yogibimbi almost 4 yearsthanks, that sort of saved my behind! I tried with the cordova plugin first, then current-device; but you're totally right, it is ridiculously easy to build it yourself. I made a directive of it and called it a day