I am trying to change the background image when mobile device motion is changed (Like you make the device top, left or right, or up-down motion). i am using this code, issue is its start working immediately, even I don't change the motion of device by hand. its keep on updating always in a loop.
what I want when I change the mobile device a bit right or left or up down, it should change image than, any idea how I can make it working:
window.addEventListener("devicemotion", function(event){
if(event.rotationRate.alpha || event.rotationRate.beta || event.rotationRate.gamma)
{
var myImages = new Array("victoria_bg.png", "victoria_bg_2.png", "victoria_bg_3.png", "victoria_bg_4.png");
var random = myImages[Math.floor(Math.random() * myImages.length)];
random = 'url(<?php echo base_url();?>resources/mobile/images/' + random + ')';
}
});
From MDN
so it's not a traditional event like
clickbut fires constantly. You'll need to store the previous event's values and compare to see if it's changed.Due to how the alpha/beta/gamma are provided, you'll likely need some tolerance. Test the exact values being returned to determine how much tolerance/sensitivity is required in your scenario.
Here's an example:
(obviously can use an object / namespacing / scope to reduce global variables)