A few weeks ago, I completed my first project where I used data from an API. I created a Random Quote Machine that shows a quote on button click, and gives you the option to post it to Twitter. When I started, it only took a quick search to find a free API from Quotes on Design whose response is in the following format.

[{"ID":141,
"title":"author",
"content":"<p>quote<\/p>\n",
"link":"https:\/\/quotesondesign.com\/jakob-nielsen\/",
"custom_meta":{
  "Source":"link"}}]

After looking at the response, I decided what data I needed and how to format it. I knew I needed the quote and the author and both of them as separate strings. I wanted to choose how I styled them myself so I didn’t need any html tags. Once this was done, I added quote icons around the quote and created a link to share on Twitter.

function getQuote(){
  $.getJSON("...", function(quote){
    $(".quote").html("<i class='fa fa-quote-left' aria-hidden='true'></i>" +
      quote[0].content.replace(/\n|<\/*p>/g,"").trim() +
      "<i class='fa fa-quote-right' aria-hidden='true'></i>");
    $(".title").html(quote[0].title);
    $(".tweet").html("<a target='_blank' href='https://twitter.com/...\"" +
      $(".quote").text() + '" -' + $(".title").text() + 
      "'><i class='fa fa-twitter fa-2x' aria-hidden='true'></i></a>");
  });
}

By now, my quote machine was working successfully most of the time. However, I found that sometimes the quotes weren't updating after the first pull, as if they were cached. I changed cache to false on load and fixed the problem. Success!


$(document).ready(function(){
  $.ajaxSetup({cache:false});
  getQuote();
  $(".new").click(getQuote);
});

Check out my GitHub repo here!

Leave a Reply

Your email address will not be published. Required fields are marked *