I know this part should have been the easiest part of the project, but I am having difficulties with generating a new quote in my random quote machine. I have tried : creating a new function; getting a new random number; using different jQuery selectors; and refreshing the page, but nothing has worked for me yet. Where am I going wrong and how should I fix it?
onClick you should call a function, onClick of button you are getting an error saying ‘x is not defined’, write one function and move logic of updating quote inside the function and call the function on button click.
function x (){
let x = myArray[Math.floor(Math.random() * myArray.length)];
return x;
};
This is what I started with in the beginning I also tried the new function with it. At first it gave me that same error so I tried making it a global variable.
in jQuery I used getElementById("new-quote").innerHTML = and nothing seemed to work.
refreshing the page, didn’t even wait for the click, it just had it on a loop
I guess I just can’t think of how logic to update the quote works
you really need to put everything in a function, all your logic to get a random number and all, because as it is everything is executed as soon as you open the page
instead you want everything to happen only when a certain event happens (probably on page load, and then on the click of a button)
let Quote = function displayQuote() {
let random = obj;
let text = random.quote;
return text;
}
let Author = function displayAuthor () {
let random = obj;
let anon = random.author;
return anon;
}
Sorry everyone for the late delay in responding, I haven’t been around my computer coding for the past few days.
My Code at the Moment:
//get global number
let num = Math.floor(Math.random() * myArray.length-1);
onload = function load () {
//get quote and author Object from array
let obj = myArray[num];
//Quote portion from Object
let Quote = function displayQuote() {
let random = obj;
let text = random.quote;
return text;
}
//Author portion from Object
let Author = function displayAuthor () {
let random = obj;
let anon = random.author;
return anon;
}
//Enter quote into the HTML
t = document.getElementById("TEXT").innerHTML = Quote();
//Enter author into the HTML
a = document.getElementById("ANON").innerHTML = Author();
}
//Get new quote
onClick = function reload (num){
return num = Math.floor(Math.random() * myArray.length-1)
}
makes the global var obj (which assigns an object from the array I created) into a local var random. After the local var was assigned, I was able to pull the author and the quote out of the object. (I did this because trying to pull them out of the object by itself was not working). After I pulled what I needed from the object, I assigned them to their own var’s.
This process should have been done on the pages load.