Is there a way of handling when the user turns from portrait to landscape view on a web application? Like when you are looking the web app on portrait view and you see the normal data.
And then when you turn your device to landscape view you get to see some different data.
My question: is there a way of accomplishing this with pure JavaScript and CSS? Or do I have to rely on a API?
UPDATE: I found a way of doing it with pure/plain JS using the Device Orientation API and I've found an example which accomplishes what I'm trying to do but I can't make it work properly because the if statement is interrupting me every time the rotation is greater than 90 and even if I put a variable to check if the rotation is already 90.
function init() {
var compass = document.getElementById('compass'),
comp = document.getElementById("comp");
if(window.DeviceOrientationEvent) {
window.addEventListener('deviceorientation', function(event) {
var alpha;
//Check for iOS property
if(event.webkitCompassHeading) {
alpha = event.webkitCompassHeading;
//Rotation is reversed for iOS
compass.style.WebkitTransform = 'rotate(-' + alpha + 'deg)';
}
//non iOS
else {
alpha = event.alpha;
webkitAlpha = alpha;
if(!window.chrome) {
//Assume Android stock (this is crude, but good enough for our example) and apply offset
webkitAlpha = alpha-270;
}
}
compass.style.Transform = 'rotate(' + alpha + 'deg)';
//THIS IS THE PART I'VE ADDED
var iftrue = false;
comp.innerHTML = alpha + "deg";
if (alpha >= 90 && alpha <= 100) {
if (!iftrue) {
alert("it is");
return iftrue = true;
};
}
else if (alpha <= 90) {console.log("it is not");
};
//TILL HERE compass.style.WebkitTransform = 'rotate('+ webkitAlpha + 'deg)';
//Rotation is reversed for FF
compass.style.MozTransform = 'rotate(-' + alpha + 'deg)';
}, false);
}
}
You can use the CSS Media Queries to detect, if a device is in landscape- or portrait. With your CSS you can define which information to show when. For example:
/* ----------- iPhone 6+ ----------- */
/* Portrait and Landscape */
@media only screen
and (min-device-width: 414px)
and (max-device-width: 736px)
and (-webkit-min-device-pixel-ratio: 3) {
/* Your styles */
}
/* Portrait */
@media only screen
and (min-device-width: 414px)
and (max-device-width: 736px)
and (-webkit-min-device-pixel-ratio: 3)
and (orientation: portrait) {
/* Your styles */
}
/* Landscape */
@media only screen
and (min-device-width: 414px)
and (max-device-width: 736px)
and (-webkit-min-device-pixel-ratio: 3)
and (orientation: landscape) {
/* Your styles */
}
See https://css-tricks.com/snippets/css/media-queries-for-standard-devices/ for more examples.