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.