Note that there are some explanatory texts on larger screens.

plurals
  1. POTake 3 random images and 1 word linked to one of those images out of a JavaScript array and displayed on screen in separate divs
    text
    copied!<p>I'm creating web game where 3 images will be displayed on screen and the user will have to click on the image that matches the word (which is also on screen)</p> <p>So far I have made a JavaScript array of the images and the words (populated from a database) and have managed to print 3 random images from the array on screen in 3 separate divs.</p> <p>At the moment I am really struggling to print a word out at the same time as the 3 images that 'belongs' to one of the random images that have been printed on screen. </p> <p>Here is my current code :- </p> <pre><code> &lt;script&gt; var items = [ &lt;?php $con = mysql_connect("localhost","*****","******"); if (!$con) { die('Could not connect: ' . mysql_error()); } mysql_select_db("learning_game", $con); $result = mysql_query("SELECT * FROM data"); $first = true; while ($row = mysql_fetch_array($result)) { if (!$first) { echo ","; } $first = false; echo "{name:'" . $row['word'] . "',image:'" . $row['image'] ."'}"; } mysql_close($con); ?&gt; ]; for (var i = 0; i &lt; items.length; i += 1) { } document.write("&lt;br /&gt; &lt;br /&gt; &lt;br /&gt;"); console.log(items); top.items = items; var images = new Array(); var list = document.getElementsByTagName('div')[0]; for(i = 0; i &lt; 3; i++) { // Choose a random item and remove it from the array var item = items.splice(Math.floor(Math.random() * items.length), 1)[0]; // Create the image element and set its src attribute images[i] = document.createElement('img'); images[i].src = item.image; // Add it to your container element } document.getElementById("one").appendChild(images[0]); document.getElementById("two").appendChild(images[1]); document.getElementById("three").appendChild(images[2]); &lt;/script&gt; </code></pre> <p>I hope to have 4 divs altogether, 1 div per image and the last div for the word that links/belongs to one of the images.</p> <p>The JavaScript Array Looks like this :-</p> <pre><code> var items = [ {name:'Coch',image:'upload/coch.png'}, {name:'Glas',image:'upload/glas.png'}, {name:'Melyn',image:'upload/melyn.png'},{name:'Ci',image:'upload/dog.jpg'}, {name:'Cath',image:'upload/cath.jpg'},{name:'Gwyrdd',image:'upload/gwyrdd.png'}, {name:'Un',image:'upload/un.jpg'},{name:'Dau',image:'upload/dau.jpg'}, {name:'Tri',image:'upload/tri.jpg'},{name:'Bochdew',image:'upload/bochdew.jpg'}, {name:'Piws',image:'upload/piws.png'} ]; </code></pre> <p>name being the 'word'. image being the link to the image in the file system.</p> <p>Any help would be great, thank you in advance. </p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload