Help with Quote Generator

Help with Quote Generator
0.0 0

#1

Hi,

Codepen for ths - https://codepen.io/ChrisMorrall/pen/xWpvoR

I’m trying to create a new jQuery function from the code to make an api call and update the quote as I need the call to run on page load as well as when the “New Quote” button is clicked so I don’t want to put the same code in twice (once on document.ready and also when the button is clicked… Looked up how to declare a jQuery function and pulled the code from below my on.click function, which was working fine under the on.click fucntion, and put into a new jQuery fuction called getRandomQuote. But I have tried different ways to call the function and none work, so could do with some help in working this out.

Thanks

Chris


#2

You’re almost there! I just did minimal corrections.

When calling functions, you need the () parenthesis.
I removed the jquery function declaration… I just declared it as normal JS function.
Then I called the function on first script execution.

Only click below if you want to see my solution, but above tips should be enough to get you going.

 $(document).ready(function() {
    getRandomQuote();
    $("#getQuote").on("click", function(){
      // Only change code below this line.
      
      getRandomQuote();
      
      // Only change code above this line.
    });

  });


    getRandomQuote= function () {
       $.getJSON("https://talaikis.com/api/quotes/random/ ", function(json) {
        // $("#quote").html(JSON.stringify(json));
        
        var html1 = "";
        var html2 = "";
        html1+='<p>"' + json.quote + '"</p>';
        html2+= json.author;
        
        $("#quote").html(html1);
        $("#bq-footer").html(html2);
  
        
      }); 
    }



#3

Thanks Owel. Working now without looking at your code. I had initialy declared it as a JS Function but I must have not been calling it correctly or there was some other problem. I wasn’t sure if you could use jQuery in a JS function hence I tried the jQuery function. When you have never written a function before it’s difficult to know whats wrong when it doesn’t work. I know I needed the brackets when calling a function - I just got to the point of trying anything and striped the brackets out and threw up my hands!