0

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.

  • 1
    You shouldn't be doing this. They don't seem to have an API, so they probably don't want people to hammer their servers with requests to non-existing images. – DanMan Jan 05 '14 at 17:23

2 Answers2

1

You can use the image's onerror handler.

First set up the handler in your init code.

var img = document.getElementById('image');

img.onerror = function() {
    console.log('Image ' + this.src + ' didn\'t load');
}

Then in your interval you just generate and set the url as usual. If an error occurs the function above will be called where you can take the necessary steps.

img.src = "http://www.puu.sh/" +generator(5) + ".jpg";

Except from that I agree with DanMan's comment - it's probably not a good idea doing this with someone else's server...

0

Solution from @Ken Fyrstenberg is elegant but you can also do

 <img id="image" src="" onerror="YouErrorFunction(this)"/>
Vova Bilyachat
  • 18,765
  • 4
  • 55
  • 80