lundi 14 septembre 2015

Pulling a random image from imgur with Javascript

I created a function with the help of some other StackOverflow answers - when the button is clicked, it generates a random image from imgur by using a 5-letter string and adding it to a url. Here's my code: http://ift.tt/1gnxC6J

function randomString() {
    var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghiklmnopqrstuvwxyz';
    var stringlength = 5;
    var text = '';
    for (var i = 0; i < stringlength; i++) {
      var rnum = Math.floor(Math.random() * chars.length);
      text += chars.substring(rnum,rnum+1);
    }
    document.getElementById('output').innerHTML = text;
    var source = 'http://i.imgur.com/' + text + '.jpg';
    $('.stuff img').attr('src', source);
    var newimagewidth = $('.stuff img').width;
    avoidBrokenImages();
  }

This is successful besides the fact that I get the "removed" image a lot, because it's pulling deleted pictures from imgur, or images that never contained the random 5-letter string. To avoid this, I'm trying to create a way to detect this image (http://ift.tt/1eXCOwg), which is 161px wide, and then re-run the function until it gets an image that is not 161px wide. I have attempted this in the Codepen above by running the following function at the end of my image generator function:

function avoidBrokenImages(){
  var newimagewidth = $('.stuff img').width;
  if ($('.stuff img').width() == 161) {
     randomString();
    } else {
      return false;
    }
}

This "avoidBrokenImages" function doesn't seem to work because I'm still getting the "removed" image a lot.

Any suggestions? I feel like this is something easy I'm missing.




Aucun commentaire:

Enregistrer un commentaire