javascripthtmldevicemotion

How to transfer 'devicemotion' property in JavaScript?


I have a DOM element (in some cases several) that I want to move (by changing the css) when the device moves.

Now, I wonder why this doesn't work:

var aDOMElement = document.getElementById("someId");
aDOMElement.DeviceMotionEvent = window.DeviceMotionEvent;
aDOMElement.addEventListener('devicemotion', motionHandler, false);

I consider a workaround to just work with the window object and in the callback I handle the movements of all objects which are stored in an array.

Kind of like this:

function motionHandler(event) {
    for (var obj in objectList) {
        obj.move(event);
    }
}

However, for some odd reason, the move function I assigned to the object before storing it in the list is undefined. Explanations and/or solutions for this are welcome.

EDIT:

Here's how I create and add the object to the array:

var objectList = [];

var elem = document.createElement("div");
//add some properties
elem.id = "someId";
elem.move = specificMoveFunction;
//add it to the list
objectList[elem.id] = elem;

Solution

  • Just because you assign a property DeviceMotionEvent to a DOM element doesn't mean it's going to be fired... You'd have to connect the event listener on the window (where it is fired) to the event listener(s) on the DOM elements and fire them manually. You'd be better off listening on the window's event and doing your DOM manipulation there.

    e.g.

    window.addEventListener('devicemotion', function(event) {
      var domElements = document.getElementsByClassName('could-move');
      for (i=0;i<elements.length;i++) { 
        elements[i].classList.add("moved"); 
      }
    });
    

    where your HTML before would look like:

    <span class="could-move">span 1</span>
    <span class="could-move">span 2</span>
    

    and after would look like

    <span class="could-move moved">span 1</span>
    <span class="could-move moved">span 2</span>
    

    EDIT:

    Actually, why do you need to set it from window onto the DOM element? can you not just aDOMElement.addEventListener('devicemotion', motionHandler, false); without aDOMElement.DeviceMotionEvent = window.DeviceMotionEvent;? The MDN docs don't say that this is ONLY fired on the window.

    EDIT II: the examples all show the event being fired only on the window: http://www.html5rocks.com/en/tutorials/device/orientation/ so I still think you are better off listening only on the window and doing your work there.