Reputation: 1
I have a list of quotes and every time I click the button I want it to go to a new quote. Can someone please explain what's wrong here and how I should fix it?
function myLost() {
var quotes = new Array();
var nextQuote = 0;
quotes[0] = "Don't be so humble - you are not that great.";
quotes[1] = "Moral indignation is jealousy with a halo.";
quotes[2] = "Glory is fleeting, but obscurity is forever.";
quotes[3] = "The fundamental cause of trouble in the world is that the stupid are cocksure while the intelligent are full of doubt.";
quotes[4] = "Victory goes to the player who makes the next-to-last mistake.";
quotes[5] = "His ignorance is encyclopedic";
quotes[6] = "If a man does his best, what else is there?";
quotes[7] = "Political correctness is tyranny with manners.";
quotes[8] = "You can avoid reality, but you cannot avoid the consequences of avoiding reality.";
quotes[9] = "When one person suffers from a delusion it is called insanity; when many people suffer from a delusion it is called religion."
function buttonClickHandler() {
nextQuote++;
// roll back to 0 if we reach the end
if (nextQuote >= quotes.length) {
nextQuote = 0;
}
}
document.getElementById('buton').addEventListener("click", buttonClickHandler, false);
}
Upvotes: 0
Views: 60
Reputation: 337560
The only issue I can see is that your code doesn't appear to be using the nextQuote
index to retrieve an element from the quotes
array. You also don't appear to invoke myLost()
anywhere, but I assume that's just been omitted from the example in the question.
Also note that you can simplify the array definition, and you can use the modulo operator to access the array without needing to reset the index to 0
. Try this:
function myLost() {
let nextQuote = 0;
let quotes = [
"Don't be so humble - you are not that great.",
"Moral indignation is jealousy with a halo.",
"Glory is fleeting, but obscurity is forever.",
"The fundamental cause of trouble in the world is that the stupid are cocksure while the intelligent are full of doubt.",
"Victory goes to the player who makes the next-to-last mistake.",
"His ignorance is encyclopedic",
"If a man does his best, what else is there?",
"Political correctness is tyranny with manners.",
"You can avoid reality, but you cannot avoid the consequences of avoiding reality.",
"When one person suffers from a delusion it is called insanity; when many people suffer from a delusion it is called religion."
];
function buttonClickHandler() {
let quote = quotes[nextQuote % quotes.length];
console.log(quote);
nextQuote++;
}
document.querySelector('#buton').addEventListener("click", buttonClickHandler, false);
}
myLost();
<button type="button" id="buton">Get quote</button>
Upvotes: 1