title: Check if an image is displayed and if not call a function?
body: <p>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 <a href="http://www.reddit.com/r/InternetIsBeautiful/comments/1ufnqw/so_today_me_and_my_friend_invented_a_new_game_nsfw/cehrfgr" rel="nofollow">this</a>.</p>
  
  <p>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.</p>
  
  <p>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?</p>
  
  <p>Here's the <a href="http://jsfiddle.net/THughes/5nXH4/" rel="nofollow">JSFiddle</a>. </p>
  
  <pre><code>&lt;body&gt;
      &lt;img id="image" src=""/&gt;
      &lt;script&gt;
          function generator(num)
              {
                  var text = "";
                  var charset = "abcdefghijklmnopqrstuvwxyz0123456789";
  
                  for( var i=0; i &lt; 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");
  
      &lt;/script&gt;
  &lt;/body&gt;
  </code></pre>
  
  <p>Thanks.</p>