Reputation: 21
I have the first part of this problem down, I am able to select a random element from the array like so
function setImage()
{
var images = ['anemone.gif', 'ball.gif', 'crab.gif', 'fish2.gif', 'gull.gif', 'jellyfish.gif', 'moon.gif', 'sail.gif', 'shell.gif', 'snail.gif', 'sun.gif', 'sunnies.gif', 'whale.gif'];
var slots = [document.getElementById('slot0'), document.getElementById('slot1'), document.getElementById('slot2')];
document.getElementById('slot0').src = images[Math.floor(Math.random() * images.length)];
document.getElementById('slot1').src = images[Math.floor(Math.random() * images.length)];
document.getElementById('slot2').src = images[Math.floor(Math.random() * images.length)];
alert(images.indexOf(document.getElementById('slot2')));
}
However the second line is not giving me the correct index of the element, and I'm not sure how else to find it?
Upvotes: 1
Views: 233
Reputation: 2099
document.getElementById('slot2')
will gove you the node (img
in this case). So you can't find this in the array containing src
values.
document.getElementById('slot2').src
will give you full path (like http://....../file.ext
), not just file name.
Use attributes property.
document.getElementById('slot2').attributes["src"]
Upvotes: 1
Reputation: 202
Is there a reason you're not just setting the random index into a variable and just using that?
function setImage()
{
var images = ['anemone.gif', 'ball.gif', 'crab.gif', 'fish2.gif', 'gull.gif', 'jellyfish.gif', 'moon.gif', 'sail.gif', 'shell.gif', 'snail.gif', 'sun.gif','sunnies.gif', 'whale.gif'];
var slots = [document.getElementById('slot0'), document.getElementById('slot1'), document.getElementById('slot2')];
var rnd0 = Math.floor(Math.random() * images.length);
var rnd1 = Math.floor(Math.random() * images.length);
var rnd2 = Math.floor(Math.random() * images.length);
document.getElementById('slot0').src = images[rnd0];
document.getElementById('slot1').src = images[rnd1];
document.getElementById('slot2').src = images[rnd2];
alert(rnd2);
}
If there is you should try alerting the source of the image and make sure that it matches in format to the images array.
If you're still having trouble, set up a jsfiddle with both html and JS so we can see what's going on.
Upvotes: 1
Reputation: 9039
Don't you mean:
alert(images.indexOf(document.getElementById('slot2').src));
Upvotes: 0