Reputation: 6103
Here's what I'm trying to achiev: I have a center circle div, that contains 5 other divs. When I rotate a device on gamma axis, I want the circle div to rotate accordingly to the gamma degree, but the 5 inner divs to rotate in counter direction (sort of create an illusion that the inner divs are not actually spinning, sort of a ferris wheel effect). I wrote this code:
document.addEventListener("DOMContentLoaded",onload);
function onload(){
if (window.DeviceOrientationEvent) {
console.log("DeviceOrientation is supported");
window.addEventListener('deviceorientation', function(eventData){
var tiltLR = eventData.gamma;
deviceOrientationHandler(tiltLR);
}, false);
} else {
console.log("DeviceOrientation NOT supported");
}
}
var lastTilt = 0;
function deviceOrientationHandler(tiltLR) {
var circle = document.getElementById('center-circle');
var str = window.getComputedStyle(circle, null);
var trans = str.getPropertyValue("-webkit-transform");
var tr_values = trans.split('(')[1],
tr_values = tr_values.split(')')[0],
tr_values = tr_values.split(',');
circle.style.webkitTransform = "translate("+tr_values[4]+"px, "+tr_values[5]+"px) rotate("+ tiltLR +"deg)"
var icons = document.getElementsByClassName('icon-circle');
tiltLR = Math.abs(tiltLR);
for (var i = 0; i <= icons.length; i++){
var el = icons[i];
var st = window.getComputedStyle(el, null);
var tr = st.getPropertyValue("-webkit-transform");
var values = tr.split('(')[1],
values = values.split(')')[0],
values = values.split(',');
if (tiltLR > lastTilt) {
icons[i].style.webkitTransform = "translate("+values[4]+"px, "+values[5]+"px) rotate(-"+ tiltLR +"deg)";
} else {
icons[i].style.webkitTransform = "translate("+values[4]+"px, "+values[5]+"px) rotate("+ tiltLR +"deg)";
}
console.log("el"+i+": "+tr+" | vals: "+values);
}
lastTilt = tiltLR;
}
The problem is inside the for
loop - when the code gets to this line var st = window.getComputedStyle(el, null);
I'm getting these error messages: Uncaught TypeError: Failed to execute 'getComputedStyle' on 'Window': parameter 1 is not of type 'Element'
. I tried to change the el
var to icons[i].id
, but it didn't help.
Any ideas why it;s happening and how to fix it?
Upvotes: 3
Views: 6398
Reputation: 8488
As @Juhana mentioned in comments, your last loop will fail because there is no element var el = icons[i]; // where i=icons.length
hence change your loop to
for (var i = 0; i < icons.length; i++){//change <= to <
and it should work.
Upvotes: 1