0

While completing a project for FreeCodeCamp I had the idea to create a simple website which can get me a random picture of a cat when pressing a button. So I found the http://thecatapi.com/ which will get me a random src so I can add it to my img tag. I've made this with jQuery as it's easier from me coming from FCC.

As the api will get me the random source url I didn't think it would be difficult, however with the code I implemented, the button which request for a cat only works the first time it's clicked.

Here is my HTML

<img class="img-fluid" src="" id="kitties">
<div class="catText"> <h1>Your cat will spawn here!</h1></div>

<div class="buttons text-center">
   <a class="btn btn-info" target="_blank" id="tweetButton">Tweet it!</a>
   <button class="btn btn-secondary" id="kittyButton"> Generate </button>
</div>

And my Javascript

$(document).ready(function() {
   $("#kittyButton").on("click", function(){
      $('.catText').remove();
      $("#kitties").attr('src','http://thecatapi.com/api/images/get')
   });
});

How can I get a different image each time I click on the button?

Thanks in advance, you can see the whole code in my codepen right HERE

1
  • 2
    Because the URL doesn't change, the browser caches the result. A simple hack is to change the URL like this: jsfiddle.net/khrismuc/p17t6bvr
    – user5734311
    Commented Jun 1, 2018 at 12:17

1 Answer 1

4

Updated codepen : https://codepen.io/anon/pen/vrNYey?editors=1010

Updated your code to add random number at the end of string as to avoid browser caching , refer : https://developer.mozilla.org/en-US/docs/Web/HTTP/Caching

 var rnd = new Date().getTime();

The above code will get EPOC time and the request will be unique every time

$(document).ready(function() {
$("#kittyButton").on("click", function(){
   $('.catText').remove();
 var rnd = new Date().getTime();

$("#kitties").attr('src','http://thecatapi.com/api/images/get?format=src&type=jpg,png?'+rnd)
// $('#tweetButton').attr('href', 'https://twitter.com/intent/tweet?text=' +('"'+HOAAAAAAAA+'"'+"  - "+GATITAAAAAAA));
      }); 
});
1
  • 1
    Wow! thank you, I'll definitely read about caching. Have a nice day!
    – Johan G.
    Commented Jun 1, 2018 at 12:42

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.