tags:

views:

131

answers:

4

Hi, I bet I've got elementary question, but I couldn't solve it for two nights. I've got 1 "ul" element and I just want it to move any amount of pixels every e.g. 2 sec to the left. I want him to move like this step by step and then come back to the original position and start moving again. I've been stucked, my script only moves it to the final position and finish.

window.onload = function moveUl(){
var eUl = document.getElementById('change');
var eLi = eUl.getElementsByTagName('li'); x = -300;

function move(){
    for(i=0;i< eLi.length;i++){
        eUl.style.marginLeft = i*x+'px'; 
    }
} 
setInterval(move,1000);

}

This is the simpliest I can think of. I know this script executes whole loop after 1 sec, but I try to do something like this : Move this element to the left, wait, move more to left and so on.

Thanks so much for your help

A: 

Is the problem you can't go back from where you started?

Why not just add a new for loop in move

    for(i=eLi.length; i>0 ;i--){
        eUl.style.marginLeft = i*x+'px'; 
    }

Do you also want it to loop for ever ie start -> left -> start -> left and again?

hhafez
+2  A: 

If you want it to slide, you have to timeout per iteration. Try writing a function that does a single shift, then calling this function every 10 ms. You can also look into a Javascript library like jQuery that provides a nice API for doing the moving.

Josh
+2  A: 

Do you mean something like this?

window.onload = function moveUl()
{
    var eUl = document.getElementById('change');
    var eLi = eUl.getElementsByTagName('li');

    var delta = 0;
    function move()
    {
        for(i=0;i< eLi.length;i++)
            eUl.style.marginLeft = (-300*i+delta)+'px'; 
        delta -= 100; // Prepares for the next step
        if ( delta == -1000 )
            delta = 0; // Resets after 10 steps
    } 
    setInterval(move,1000);
}
Vilx-
A: 

Thank you Vilx! That works! I must learn.

perfectDay