0

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?

4
  • 1
    Looks like that suggestion wasn't so great. Styles like margin-left: -1px; are not cumulative when applied several times. You would be better off mutating the DOM element's style directly instead. Commented Aug 10, 2015 at 14:40
  • After the first iteration of the loop you would be just re-updating the class name of each element to the class name they all already have. It's not an accumulative effect. You need to move the element with inline css attributes. Class names won't work in this case. Commented Aug 10, 2015 at 14:41
  • How can I do this with javascript? Commented Aug 10, 2015 at 14:42
  • Are you trying to do an animation? Commented Aug 10, 2015 at 14:47

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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--;
   }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.