Reputation: 597
I have a html page of 9 images which must change their order when page is reloaded I have placed image as 3 rows and 3 columns which on reload should change the order of the image .
Here is my HTML Code
<html>
<head>
<script type="text/javascript">
var len = document.images.length;
var images = document.images;
var img = function (){
for(var j, x, i = images.length; i; j = parseInt(Math.random() * i), x = images[--i], images[i] = images[j], images[j] = x);
}
window.onload = function(){
for(var i = 0 ; i < len ; i++)
{
images[i].src = img[i].src;
}
}
</script>
</head>
<body>
<table>
<tr>
<td id="cell1"><button value="1"><img src="1.jpg" width="42" height="42"/></button></td>
<td id="cell2"><button value="2"><img src="2.jpg" width="42" height="42"/></button></td>
<td id="cell3"><button value="3"><img src="3.jpg" width="42" height="42"/></button></td>
</tr>
<tr>
<td id="cell4"><button value="4"><img src="4.jpg" width="42" height="42"/></button></td>
<td id="cell5"><button value="5"><img src="5.jpg" width="42" height="42"/></button></td>
<td id="cell6"><button value="6"><img src="6.jpg" width="42" height="42"/></button></td>
</tr>
<tr>
<td id="cell7"><button value="7"><img src="7.jpg" width="42" height="42"/></button></td>
<td id="cell8"><button value="8"><img src="8.jpg" width="42" height="42"/></button></td>
<td id="cell9"><button value="9"><img src="9.jpg" width="42" height="42"/></button></td>
</tr>
</table>
<!-- forms's action sends the data to a specified php page -->
<form action="pictures.php" method="post">
<input id="pswd" type="hidden" value="" name="pass">
</form>
</body>
</html>
I Cant randomize the image . Any Suggestion on what i am doing wrong :)
Upvotes: 1
Views: 133
Reputation: 4387
You should "randomize" your array:
<script type="text/javascript">
var len = document.images.length;
var images = document.images;
var img = function (){
for(var j, x, i = images.length; i; j = parseInt(Math.random() * i), x = images[--i], images[i] = images[j], images[j] = x);
}
img = shuffle(img);//this "randomizes" the 'img' array using the function bellow
window.onload = function(){
for(var i = 0 ; i < len ; i++)
{
images[i].src = img[i].src;
}
</script>
And paste this function in your code: https://stackoverflow.com/a/2450976/3132718
Upvotes: 1