I am struggling to take 3 random images (No repeat) out of my Javascript array and print them on screen within separate Divs.
My Javascript array is being populated by a database which contains the links/location of the images on the server.
Currently my page looks like this:
<html>
<head>
</head>
<body>
<div></div>
<script>
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'} ];
for (var i = 0; i < items.length; i += 1) {
document.getElementsByTagName('div')[0].innerHTML += items[i].name + " / " + items[i].image + "<br />\n";
}
</script>
</body>
</html>
This code simply takes the image links from the database and inserts them into a javascipt array. (And prints the links on screen at the moment)
Can anyone give me any help on how to get this to work? Take 3 random images links from that array (No duplication's), and display the 3 images on screen in 3 different divs.
I am not good with javascipt at all and any code examples would be great.
Thank You in advance for any replies.
Assuming the links to the image sources are correct relative to the page that the images will be on, this should do the trick:
Note that this will modify the 'items' array, so if you need it later you will need to copy the array first or tweak the logic.
JSFiddle: http://jsfiddle.net/ynhCN/1/
Shuffle your array and then take the first three items. Here you can find a nice function to shuffle arrays: How to randomize (shuffle) a JavaScript array?