radgokart
radgokart

Reputation: 45

Not able to set style properties with JavaScript

I'm trying change the following code:

var items = document.querySelectorAll('.mover');
for (var i = 0; i < 60; i++) {
  var phase = Math.sin((document.body.scrollTop / 1250) + (i % 5));
  items[i].style.left = items[i].basicLeft + 100 * phase + 'px';
}

into this...

var items = document.querySelectorAll('.mover');
for (var i = 0; i < 60; i++) {
  items[i].style.left = items[i].basicLeft + 100 * phases[i % 5] +  
  'px';
  console.log(items[i].style.left);
}

Variable phases is an array that is global in scope and defined elsewhere in the js file. The console.log() output is showing me that the assignment is working properly, but the page isn't updating when I use the static phases array instead of the Math.sin() function.
I've tried other solutions, but if I'm not passing result of Math.sin(), it doesn't work. I'm doing this to avoid having to call Math.sin on every iteration.

Here is the CSS, which hasn't changed:

.mover {
  position: fixed;
  width: 256px;
  z-index: -1;
}

Upvotes: 0

Views: 90

Answers (1)

Alvaro Silvino
Alvaro Silvino

Reputation: 9733

Here Is a way!

var items = document.querySelectorAll('.mover');
var phase = []
for (var i = 0; i < 5; i++) {
  phase.push(Math.sin((document.body.scrollTop / 1250) + (i % 5)));
}

for (var i = 0; i < 60; i++) {
  items[i].style.left = items[i].basicLeft + 100 * phases[i % 5] +  
  'px';
  console.log(items[i].style.left);
}

Upvotes: 1

Related Questions