apologies if this is a stupid question, but I'm not too good with JavaScript yet, I'm trying to make a page that will fetch a random image from puu.sh and display it on a page, sort of inspired by this.
I know it is probably not the most elegant solution but I have a function that generates a random string of 5 characters and will then add that to a puu.sh link and display the image.
This works if an image with that string exists, but 9 times out of 10 an image doesn't exist. I'm looking for a way to check if the image exists, and then if not, go back to the function and create another string and load another image until an image is displayed, is there a way to do this?
Here's the JSFiddle.
<body>
<img id="image" src=""/>
<script>
function generator(num)
{
var text = "";
var charset = "abcdefghijklmnopqrstuvwxyz0123456789";
for( var i=0; i < num; i++ )
text += charset.charAt(Math.floor(Math.random() * charset.length));
return text;
}
document.getElementById('image').setAttribute('src', "http://www.puu.sh/" +generator(5) + ".jpg");
</script>
</body>
Thanks.