Question:
deviceorientation events won’t trigger on mobile
Product:
Editor
What are you trying to achieve:
I’m trying to create a site which is sensitive to the device orientation (e.g. tilt)
What have you already tried:
I’ve placed an HTML element on the page, with the following code, based on MDN example here
the code in the element can be found below.
What happens:
- I get the events when testing the site on desktop (using chrome dev-tools sensor API)
- I get the events playing with the MDN example
- I don’t get the events on my site on mobile
Could this be related to the fact that the HTML code runs in an IFrame? see here
Note - I’m not communicating with the page yet - just want to see the green dot moving.
Additional information:
HTML code:
<html>
<head>
<meta charset="utf-8">
<meta name="robots" content="noindex, nofollow">
<style>
body {
padding: 0;
margin: 0;
}
svg:not(:root) {
display: block;
}
.playable-code {
background-color: #f4f7f8;
border: none;
border-left: 6px solid #558abb;
border-width: medium medium medium 6px;
color: #4d4e53;
height: 100px;
width: 90%;
padding: 10px 10px 0;
}
.playable-canvas {
border: 1px solid #4d4e53;
border-radius: 2px;
}
.playable-buttons {
text-align: right;
width: 90%;
padding: 5px 10px 5px 26px;
}
</style>
<style>
.garden {
position: relative;
width: 200px;
height: 200px;
border: 5px solid #ccc;
border-radius: 10px;
}
.ball {
position: absolute;
top: 90px;
left: 90px;
width: 20px;
height: 20px;
background: green;
border-radius: 100%;
}
</style>
<title>Detecting device orientation - orientation_example - code sample</title>
</head>
<body>
<div class="garden">
<div class="ball"></div>
</div>
Hold the device parallel to the ground. Rotate along its x and y axes to see the
ball move up/down and left/right respectively.
<pre class="output"></pre>
<script>
const ball = document.querySelector(".ball");
const garden = document.querySelector(".garden");
const output = document.querySelector(".output");
const maxX = garden.clientWidth - ball.clientWidth;
const maxY = garden.clientHeight - ball.clientHeight;
function handleOrientation(event) {
let x = event.beta; // In degree in the range [-180,180)
let y = event.gamma; // In degree in the range [-90,90)
output.textContent = `beta: ${x}\n`;
output.textContent += `gamma: ${y}\n`;
// Because we don't want to have the device upside down
// We constrain the x value to the range [-90,90]
if (x > 90) {
x = 90;
}
if (x < -90) {
x = -90;
}
// To make computation easier we shift the range of
// x and y to [0,180]
x += 90;
y += 90;
// 10 is half the size of the ball
// It centers the positioning point to the center of the ball
ball.style.left = `${(maxY * y) / 180 - 10}px`; // rotating device around the y axis moves the ball horizontally
ball.style.top = `${(maxX * x) / 180 - 10}px`; // rotating device around the x axis moves the ball vertically
}
window.addEventListener("deviceorientation", handleOrientation);
</script>
</body>
</html>
</body>
</html>