Rob Little
Rob Little

Reputation: 35

move object using css

I have an array of image objects:

var pics = ["pic1","pic2","pic3","pic4","pic5","pic6"]

I want to loop through and set the style.left value to 1 less than the current value. This loop iterates 100 times.

I got a great suggestion here to use css for this. I created a style called move:

margin-left: -1px;

This works great the first time through the loop:

for (i = 0; i < 100; i++) { 
for (j = 0; j < 6; j++) { 
var image = document.getElementById(pics[j]);
image.className = image.className + " move"
}
}

The problem is the images do not move after the first iteration though the loop. Any ideas what I can do?

Upvotes: 0

Views: 121

Answers (2)

IfTrue
IfTrue

Reputation: 543

The images do not move after the first iteration because you are applying the move class which sets the margin left to -1. Note it does not subtract 1 from their current left margin it sets it to -1.

So lets say it starts out with a left margin of 10 . When it goes through this loop I think you are expecting it to have a left margin of 9 to move it one pixel closer to the left side of the screen. Instead when it goes through this loop it will skip all the way -1 as the left margin because you are explicitly telling it to do that with your move class.

What you really want to do is use javascript to grab its current left margin , subtract 1 from that and then reset the left margin as the new, now less one, number.

At quick glance I think this tutorial could help you.

Upvotes: 1

scrappedcola
scrappedcola

Reputation: 10572

You can save off the margin variable and apply css with this:

var margin = -1;
for (i = 0; i < 100; i++) { 
   for (j = 0; j < 6; j++) { 
      var image = document.getElementById(pics[j]);
      image.style.marginLeft =  margin + "px";
      margin--;
   }
}

Upvotes: 0

Related Questions