Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trial
Samuel Glister
12,471 PointsGenerating a random image with a link
Hi All,
I'm at work and I need to try and generate a random image with a link behind it. This code will then need need to post itself inside of an div with the ID of "image".
Here is what I have so far:
var total_images = 3;
var random_number = Math.floor((Math.random()*total_images));
var random_img = new Array();
random_img[0] = '<a href="page1.html"><img src="1.gif"></a>';
random_img[1] = '<a href="page2.html"><img src="3.gif"></a>';
random_img[2] = '<a href="page3.html"><img src="4.gif"></a>';
document.getElementById('image').innerHTML = random_img[random_number];
However nothing displays in my div. Can anyone help? Thanks
2 Answers
Lucas Santos
19,315 PointsThis works, play around with it.
var total_images = 3;
var image = document.getElementById('image');
var random_number = Math.floor((Math.random()*total_images));
var random_img = [];
random_img[0] = '<a href="https://google.com"><img src="http://placehold.it/350x150"></a>';
random_img[1] = '<a href="https://google.com"><img src="http://placehold.it/350x250"></a>';
random_img[2] = '<a href="https://google.com"><img src="http://placehold.it/350x350"></a>';
image.innerHTML = random_img[random_number];
Samuel Glister
12,471 PointsHi Lucas,
That is perfect - just what I was looking for. Missed my morning coffee didn't i...
Thank you Sam
Lucas Santos
19,315 Pointsno problem