1

i have a 6x6 html-table. Each <td> holds <img id="1back" src="" /> where the id of each img-element is declared as "1back" to "36back". Further I have 18 .jpg files named "1.jpg" to "18.jpg". Each image has to appear in the grid twice , distributed randomly.

I am trying to accomplish this as follows:

    function PopulateGrid() {

        for (var i = 1; i <= 18;i++) //For each image file
        {
            var randomnumber = Math.floor(Math.random() * (36 - 1 + 1)) + 1; // get random # 1-36


            while (document.getElementById(randomnumber + "back").src != "")
            {
              //if the randomly chosen <img> id is not "" genrate another random number
               randomnumber = Math.floor(Math.random() * (36 - 1 + 1)) + 1;
            }

            document.getElementById(randomnumber + "back").src = "Images/" + i + ".jpg";


            //Doing this twice as every image has to appear twice
            while (document.getElementById(randomnumber + "back").src != "") {
                randomnumber = Math.floor(Math.random() * (36 - 1 + 1)) + 1;
            }

            document.getElementById(randomnumber + "back").src = "Images/" + i + ".jpg";
        }
    }

I am running into wierd behavior in IE, Chrome and FireFox. The script fails in the first while condition. It seems to me like some endless loop. I do not get any error message the page simply never stops loading.

I guess this must be something obvious as usual but I simply can't see the problem here.

チーズパン
  • 2,752
  • 8
  • 42
  • 63
  • `while (document.getElementById(randomnumber + "back").src != "") {...` I don't see anything in the `while` loop that would set the `.src` to `""`. – six fingered man May 23 '15 at 18:01
  • 3
    You could try a different approach: Create an array of 36 elements, where each number from 1 to 18 appears twice, `[ 1, 1, 2, 2, ... , 18, 18]`, [shuffle it](http://stackoverflow.com/questions/2450954/how-to-randomize-shuffle-a-javascript-array), then assign the image sources in a single loop. – Gabriel Negut May 23 '15 at 18:08
  • hi, I agree you may take another approach to implement it. For this piece of code, maybe you can put a console.log() statement inside the while loop to log the random number generated, and see if it takes too long to randomly generated the number. – Surely May 23 '15 at 18:17

1 Answers1

1

Try with console to see src of your img, when you set src to "" you'll most likely get your base url, so your != "" will never be false. Try setting your img like this:

<img id="1back">

Then src != "" should validate until you assign a src.

Julien Grégoire
  • 16,864
  • 4
  • 32
  • 57