Scramble Images- Javascript -
i have 3x4 table of images want scrambled puzzle. there total of 12 separate gifs. need is, using strictly javascript, how set randomly scrambles images every time page loads? far, have loaded images array so:
incomplete js:
var imgarray = new array(); imgarray[0] = new image(); imgarray[0].src = 'pic_01.gif'; imgarray[1] = new image(); imgarray[1].src = 'pic_02.gif'; imgarray[2] = new image(); imgarray[2].src = 'pic_03.gif'; imgarray[3] = new image(); imgarray[3].src = 'pic_04.gif'; etc... pic_05.gif... my html:
<table> <tr> <th> <img src="pic_01.gif" onclick="imageswap()" alt="" border= height=100 width=100></img> </th> <td> <img src="pic_02.gif" alt="" border= height=100 width=100></img></td> <td> <img src="pic_03.gif" alt="" border= height=100 width=100></img></td> </tr> <tr> <td> <img src="pic_04.gif" alt="" border= height=100 width=100></img></td> <td> <img src="pic_05.gif" alt="" border= height=100 width=100></img></td> <td> <img src="pic_06.gif" alt="" border= height=100 width=100></img></td> </tr> <tr> <td> <img src="pic_07.gif" alt="" border= height=100 width=100></img></td> <td> <img src="pic_08.gif" alt="" border= height=100 width=100></img></td> <td> <img src="pic_09.gif" alt="" border= height=100 width=100></img></td> </tr> <tr> <td> <img src="pic_10.gif" alt="" border= height=100 width=100></img></td> <td> <img src="pic_11.gif" alt="" border= height=100 width=100></img></td> <td> <img src="pic_12.gif" alt="" border= height=100 width=100></img></td> </tr> </table> what able have user click 1 'randomized' image , swap 'randomized' image, solve puzzle. input appreciated! thanks!
i think best bet add class (let's random) each img element:
<img src="pic_10.gif" class="random" alt="" height=100 width=100 /> then can images simple queryselectorall:
var images = document.queryselectorall('.random'); randomize array of srcs:
var srcs = ['pic_01.gif', 'pic_01.gif', etc, etc]; srcs = srcs.sort(function() { return math.random() > 0.5; }); then iterate on images, applying new src each:
for (var = 0; < images.length; ++i) { images[i].src = srcs[i]; } the full function being:
var imageswap = function() { var images = document.queryselectorall('.random'); var srcs = ['pic_01.gif', 'pic_01.gif', etc, etc]; srcs = srcs.sort(function() { return math.random() > 0.5; }); (var = 0; < images.length; ++i) { images[i].src = srcs[i]; } };
Comments
Post a Comment