Question

I want to create a 2x2 button "array" (it looks like an array but it is not, it is being created by the for loop) every time I press the play button. I use the for loop to print the lines and inside the loop I use the var buttons and an "if", which appends a br, to print the new line. Although it seems that it does print the br in the for loop, when he finishes the for loop the br disappear (I use an alert "bug" to show this).
var table1 = ["1","2","3","4"];

        function shuffle(array) {
            var currentIndex = array.length, temporaryValue,randomIndex;

            // While there remain elements to shuffle...
            while (0 !== currentIndex) {

             // Pick a remaining element...
            randomIndex = Math.floor(Math.random() * currentIndex);
             currentIndex -= 1;

             // And swap it with the current element.
             temporaryValue = array[currentIndex];
            array[currentIndex] = array[randomIndex];
            array[randomIndex] = temporaryValue;
            }
            return array;
        }


        function printButtons(table1){
            shuffle(table1);
            var buttons = 0;
            var y,t;
            var mybr = document.createElement('br');
      var par = document.getElementById("div2");
            document.body.appendChild(mybr);
            for(var i =0 ; i<4; i++){
                 y = document.createElement("button");
                   t = document.createTextNode(table1[i]);
                   y.setAttribute("id",table1[i]);
                   y.appendChild(t);
                   document.body.appendChild(y);

                   buttons=buttons+1;
                   if(buttons== 2){
                        alert("bug");
                        buttons= 0 ;
            document.body.appendChild(mybr);
          }  


            }
      document.body.appendChild(mybr);

          } 



    </script>
  <div id="div1">
    <button type="button" onclick="printButtons(table1)">play</button>
    <br>
  </div>

  <div id ="div2"></div>    

</body> 

Was it helpful?

Solution

When you appendChild(mybr) and the mybr is already in the DOM, it will be moved to the new location. The fix is to create a new <br/> everytime you need to insert one:

    buttons = buttons + 1;
    if (buttons == 2) {
        buttons = 0;
        document.body.appendChild(document.createElement('br'));
    }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top