2

I have a list of names; and I want to display these names one by one. The name should apear in the top of a container, subsequently move to the bottom, and then disapear. In the mean time, the next name should have appeared in the top of the container, started moving,..., etc.

I'm not that for yet: I still need to create the code which makes the divs move; I'll do that later and it is maybe easier to create a separate function for that.

I realize very well the way in which I'm trying to achieve this is very likely too cumbersome, but I'm just a beginner... So for I made:

function myNamesFunction() {} {

  var y = 0;
  for (y = 0; y < document.getElementById("namelistID").getElementsByTagName('div').length;y++)

 {

 var vinden2 = document.getElementById("namelistID").getElementsByTagName('div')[y];

 {

  var div = document.createElement("div");
  div.innerHTML = (document.getElementById("namelistID").getElementsByTagName('div')[y].innerHTML);

  setTimeout(function () {
    document.getElementById("namecontentbox").appendChild(div)[y];
  }, 0000);
  setTimeout(function () {
    document.getElementById("namecontentbox").removeChild(div)[y];
  }, 2000);


 }

 }

}

The Html code is:

<div id="namelistID" style="display: none;">
  <div class="nameofperson">Person1</div>
  <div class="nameofperson">Person2</div>
  <div class="nameofperson">Person3</div>
  <div class="nameofperson">Person4</div>
</div>
<div id="namecontentbox"></div>

The problem is now that since I added the "settimeout", only the last item from the array seems to be created and removed. How can I start with the first, and then let each item appear and disappear?

(Any other advice on how to continue (or restart...) is very welcome too)

  • possible duplicate of [loop through a javascript object](http://stackoverflow.com/questions/11581742/loop-through-a-javascript-object) – Denys Séguret Jan 06 '13 at 15:37

1 Answers1

2

That's a classical problem, due to y's value changing by the time the function you give to setTimeout is called.

The classical solution is to protect y with a closure in your loop :

  for (y = 0; y < document.getElementById("namelistID").getElementsByTagName('div').length;y++) {
    (function(y){
      // use y
    })(y);
  }

This function is the scope of the new y variable and, as it's immediately executed, it keeps protected the value y had at this time.

If you want the timeout to be executed one after the other, and not all at the same time, increment the time :

  setTimeout(function () {
    document.getElementById("namecontentbox").removeChild(div)[y];
  }, 2000*(y+1));
Denys Séguret
  • 355,860
  • 83
  • 755
  • 726