Random Quote Machine: DRY with jQuery

Hello, sorry if this is the billionth Random Quote Machine post. I’d love any feedback on mine at: http://codepen.io/peterjmartinson/pen/jrVPBj

One question I have, is that I have two sets of $.getJSON calls - the first populates the quote when the page first loads, the second does the same when the user presses the button. They’re identical calls, so I would love to make them into a function that gets called twice, so the code isn’t repeated. However, I can’t figure out how to do it, because the calls are asynchronous - my element variable gets set before the AJAX call is completed. The commented out part shows my attempt. Any advice would be greatly appreciated!

Thanks, Peter

Hey Peter,

Your idea of wrapping the logic for the ajax calls into a function was the right one.
However, as the code is exactly the same in both cases and it is creating the side effect of updating the document as well, you do not need to declare any variable in your function, and you do not need to return anything, you could also wrap both ajax calls in a single function instead of declaring two, since both calls will be made at the same time anyway.

In the end your code would look something like this :

var getQuote = function() {
//put ajax logic here
}

getQuote(); //call your ajax function once when the document is ready

$("#getMessage").on(“click”, getQuote); // call your ajax function every time the button is clicked.

Hope this makes sense, you will have to populate the getQuote function yourself but this is really just copying and pasting what is already in your code :slight_smile:

Best,
Sylvain

Edit : It was probably unclear, but the code I pasted above is not complete, you should keep the document ready and var declaration at the top, as well as the tweet click event handler.

1 Like

Thank you @hihuz! Especially, thank you for explaining the principle of the “side effect”. My corrected code is on the CodePen, but I also pasted it below for convenience.

Peter

$(document).ready(function() {

  var getQuote = function() {
    $.getJSON( "http://api.icndb.com/jokes/random", function ( response ) {
      $( "#quote" ).html( response.value.joke );
    });
    $.getJSON( "http://uinames.com/api/?region=germany", function( response ) {
      $( "#author" ).html( "- " + response.name + " " + response.surname );
    });
  }

  getQuote();

  $("#getMessage").on("click", getQuote);

  $("#postTweet").on("click", function() {
    var quote = document.getElementById("quote").innerHTML;
    if ( quote.length <= 140 ) {
    var twtLink = 'http://twitter.com/home?status=' +encodeURIComponent(quote);
    window.open(twtLink,'_blank');
    } else {
      alert("Quote is too long to post!");
    }
  });

});