Loading JSON into a div and change background color on button click at the same time

After a couple of hours struggling with the first part I finally made it work.

However I would like to nest two additional functions, the first one to generate a random color and the second one to set the random color into a div with id #gradient that represents the background.

Here is the code so far, can you help me please?

$(document).ready(function() {
      $("#btn").on("click", function() {
        $.getJSON("http://api.forismatic.com/api/1.0/?method=getQuote&lang=en&format=jsonp&jsonp=?", function(json) {
          var quote = json.quoteText;
          var author = json.quoteAuthor;
          $(".quoteText").text("'" + quote + "'");
          $(".quoteAuthor").text("-" + author + "-");


        function RandomColor() {
          var letters = '0123456789ABCDEF';
          var color = '#';
          for (var i = 0; i < 6; i++) {
            color += letters[Math.floor(Math.random() * 16)];
          }
          return color;
        }

        function changeColor() {
              $("#gradient").css("background-color", RandomColor()));}});});});

1 answer

  • answered 2018-01-14 14:35 Chayemor

    JQuery docs:

    jQuery.getJSON( url [, data ] [, success ] )

    Looking at your code, you got that down. You are sending a function callback when you call $.getJSON(). To start debugging it, I would first tidy up the code (don't do that to yourself or future coders, your editor most likely has a "reformat code" option to add appropriate indentations. Debugging untidy code like that will give you headaches in the future.)

    Your code turns into this once you tidy it up and fix some closing/openings that are wrong.

    $(document).ready(function () {
    
        $("#btn").on("click", function () {
    
            $.getJSON("http://api.forismatic.com/api/1.0/?method=getQuote&lang=en&format=jsonp&jsonp=?", function (json) {
                var quote = json.quoteText;
                var author = json.quoteAuthor;
                $(".quoteText").text("'" + quote + "'");
                $(".quoteAuthor").text("-" + author + "-");
    
    
                function RandomColor() {
                    var letters = '0123456789ABCDEF';
                    var color = '#';
                    for (var i = 0; i < 6; i++) {
                        color += letters[Math.floor(Math.random() * 16)];
                    }
                    return color;
                }
    
                function changeColor() {
                    $("#gradient").css("background-color", RandomColor());
                }
            });
    
        });
    
    });
    

    First problem

    function changeColor() {
        $("#gradient").css("background-color", RandomColor());
    }
    

    That function will never get called. You are merely declaring it, not calling it. Just take what's inside out of it, and you've got it. I would also take the function RandomColor() (I didn't check if it works or not...) outside of that scope, in case you want to reuse it.

    You end up with this:

    $(document).ready(function () {
    
        $("#btn").on("click", function () {
    
            $.getJSON("http://api.forismatic.com/api/1.0/?method=getQuote&lang=en&format=jsonp&jsonp=?", function (json) {
                var quote = json.quoteText;
                var author = json.quoteAuthor;
                $(".quoteText").text("'" + quote + "'");
                $(".quoteAuthor").text("-" + author + "-");
    
                $("#gradient").css("background-color", RandomColor());
            });
    
        });
    
    });
    
    function RandomColor() {
        var letters = '0123456789ABCDEF';
        var color = '#';
        for (var i = 0; i < 6; i++) {
            color += letters[Math.floor(Math.random() * 16)];
        }
        return color;
    }
    

    In addition, you will only be changing the color of the divupon success. If you want to do something upon failure, use the following:

    The Promise interface in jQuery 1.5 also allows jQuery's Ajax methods, including $.getJSON(), to chain multiple .done(), .always(), and .fail() callbacks on a single request, and even to assign these callbacks after the request may have completed. If the request is already complete, the callback is fired immediately.

    $.getJSON("...", function (json) {
        ...
    }).fail(function() {
        console.log( "error" );
    });
    

    Hope that helped.