I would like to move an element to the left using a loop

I bet I have a rudimentary question, but I couldn't solve it for two nights. I have 1 "ul" element and I just want it to move any number of pixels each for example. 2 sec to the left. I want it to go step by step step by step and then return to the starting position and start moving again. I am stuck, my script only moves it to the end position and ends.

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 simplest I can think of. I know this script does a full loop after 1 second, but I'm trying to do something like this: move this element to the left, wait, move more to the left, and so on.

0


source to share


3 answers


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

      

+2


source


If you want it to slide, you need to wait out the iteration time. Try to write a function that does one shift and then calls that function every 10ms. You can also look into a Javascript library like jQuery , which provides a nice API for performing navigation.



+2


source


A problem you can't go back where did you start from?

Why not just add a new for loop to move

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

      

You also want it to loop forever i.e. start → left → start → left and again?

0


source







All Articles