Imagine that you are in a situation, on which you are wondering among 8 different choices. Thus, the following program would be able to help you take a solution. Or at least to check the way JS works with arrays, pictures, functions and buttons.
Here is what the code does – it loads 8 pictures with the trivial names pic1 to pic8 from the code folder:
Then it randomizes them. You may randomize, until you get one picture, repeated everywhere. Sooner or later (after about 10 randomizations) this would happen, because of the code and its author:
So, if you have decided that if the koala is selected over the others you will stay at home and sleep – so be it! 🙂
Here comes the code with the tricky randomization:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 |
<html> <head> <title>VitoshAcademy</title> <script> function change_1() { location.reload(); } function some_random() { return Math.floor((Math.random()*document.images.length)); } function change_2() { var pics = [ "pic1.jpg", "pic2.jpg", "pic3.jpg", "pic4.jpg", "pic5.jpg", "pic6.jpg", "pic7.jpg", "pic8.jpg" ]; for (i=0; i<document.images.length; i++) { var k = some_random(); document.images[i].src = document.images[k].src; } document.images[k].src = pics[k]; } var size = 100; </script> </head> <body> <img src="pic1.jpg" height="100" width="100"/> <img src="pic2.jpg" height="100" width="100"/> <img src="pic3.jpg" height="100" width="100"/> <img src="pic4.jpg" height="100" width="100"/> <img src="pic5.jpg" height="100" width="100"/> <img src="pic6.jpg" height="100" width="100"/> <img src="pic7.jpg" height="100" width="100"/> <img src="pic8.jpg" height="100" width="100"/> <p> <form> <input type="Button" value="Restore Order" onClick="change_1();"/> <p> <input type="Button" value="Randomize Me!" onClick="change_2();"/> </form> <script> var i; for (i=0; i<document.images.length; i++) { document.write("Picture " + i + "<br>"); document.write("Width " + document.images[i].width + "<br> "); document.write("Height " + document.images[i].height + "<br>"); document.write("File " + document.images[i].src + "<hr>"); } </script> </body> </html> |
If you remove line 34, the pics would be made equal pretty faster.
Enjoy the code! 🙂
Available in GitHub here.