0

I am trying to change the margin of each element, using setAttribute.

How can I able to use my variable dist "distance" to decrease value until 10, every after delay "interval"?

var dist=200; var speed = 2000;

function slideLeft(x){
    dist--; 
    slideSet[x].setAttribute("style","margin-right:"+dist+"px;");   
    setTimeout(slideLeft(x), delay);    
}

Take these style and elements for example...

.widiv { margin-right:200px; }

<div>
    <div class="widiv" ></div>
    <div class="widiv" ></div>
</div>

Thanks a lot.

Urg Mu
  • 56
  • 6

1 Answers1

0

Here's your code with some changes: See fiddle http://jsfiddle.net/chrismoutray/4p3xX/

var dist = 200, delay = 500,
    slideSet = document.getElementsByTagName('div');

function slideLeft(x) {
    dist--;
    if (dist < 0) return;
    slideSet[x].setAttribute("style", "margin-right:" + dist + "px;");
    setTimeout(function() {
        slideLeft(x);
    }, delay);
}

slideLeft(1);

With a few additions to the styling:

.widiv { 
    margin-right:200px; 
    float:left; 
    width: 100px; 
    border: 1px solid black; 
    height: 100px; }

The main differences are that when calling setTimeout I'm using a function delegate (function() { <your code here> }) to call the slideLeft method so that x variable is used correctly - I don't think you can pass a statement into setTimeout without doing it this way.

Also in styling the divs I made sure to include a float left other wise the change to margin right doesn't make sense - should this be margin left instead?

Chris Moutray
  • 18,029
  • 7
  • 45
  • 66
  • I just haven't posted every detail. I have sufficient styling including float and margin. My problem was the timer. Thank you for the help, its working fine now. +15 rep for you mister :) – Urg Mu Nov 14 '12 at 10:43