Button click working in JSFiddle but not chrome (Random Quote Generator)

Button click working in JSFiddle but not chrome (Random Quote Generator)
0

#1

I am still very new at this,

I do not understand why the same code will execute in one system and not another

My code (in Github) will not generate the random quote in the Chrome browser (Google Chrome 60.0.3112.90 (Official Build) (64-bit) (cohort: Stable)) I am using, but if I enter the code into JSFiddle It works as designed.

Can someone tell me why that might be happening


#2

You need to wrap your entire js code with the following:

$(document).ready(function() {
  var genNumber = Math.floor(Math.random() * 1000000);
  var url =
    "https://api.forismatic.com/api/1.0/?method=getQuote&key=" + genNumber + "&format=jsonp&lang=en&jsonp=?";

  var getQuote = function(data) {
    $("#text").text(data.quoteText);

    if (data.quoteAuthor === "") {
      data.quoteAuthor = "Unknown";
    }
    $("#author").text(data.quoteAuthor);
  };

  $("#new-quote").click(function() {
    $.getJSON(url, getQuote, "jsonp");
  });

    $.getJSON(url, getQuote, "jsonp");
});

You had your $(document).ready(function() { in the wrong location and so you were trying to create an event handler for the new-quote button before the page loaded. The entire code needs to be wrapped in the $(document).ready(function() { See above for the correct code.


#3

Thanks @rmdawson71. Works like a charm now.