Reputation: 61
I am writing some jQuery code that i want to detect the mobile devices orientation whether portrait or landscape.
I have already tried while statements but they send my test alert constantly with no avail.
my jQuery:
function test() {
if (window.matchMedia("(orientation: portrait)").matches) {
alert('You are in portrait!');
}
else if (window.matchMedia("(orientation: landscape)").matches) {
alert('You are in landscape!');
}
}
test();
Currently this runs as soon as you load into the page so that I could test the results. What I would like it to do is detect if the device is using landscape and change some CSS if it is. The problem is is that it works properly at detecting it just when I turn the device into landscape it does not detect properly. It detects portrait or landscape if I refresh the page while i have the device in that orientation. What I want to happen is for it to detect all the time as soon as I put the device into landscape mode I want it to change the CSS to the proper CSS for landscape and when it goes back to portrait I want it to change back to the original CSS. But in this case for testing and for you guys I want it to alert properly every time I change the device orientation not when i refresh the page in that orientation.
Upvotes: 1
Views: 3537
Reputation: 2386
Use orientationchange
. It is fired when the orientation of the device has changed. You can find more about this from here: https://developer.mozilla.org/en-US/docs/Web/API/Window/orientationchange_event
function detectMobileOrientation() {
switch(screen.orientation.angle) {
case 90:
case 270:
alert('landscape' + screen.orientation.angle);
break;
default:
alert('portrait' + screen.orientation.angle);
break;
}
}
window.addEventListener("orientationchange", detectMobileOrientation);
detectMobileOrientation()
You can test this directly using this link. I have tested the code on Android 9 and it is working fine for me.
Upvotes: 0
Reputation: 61
I actually just figured out a way using the switch method. For some reason case -90 || 90: was not working properly so i just made one for each proper orientation like so.
function doOnOrientationChange() {
switch(window.orientation) {
case 90:
alert('landscape');
break;
case -90:
alert('landscape');
break;
case 0:
alert('portrait');
break;
case 180:
alert('portrait');
break;
default:
break;
}
}
window.addEventListener('orientationchange', doOnOrientationChange);
// Initial execution if needed
doOnOrientationChange();
Thank you everyone for your help! This works for me on all devices I have to test on!
Upvotes: 3