I'm new to JavaScript and I was making a random quote generator but I can't seem to get my js code to link to the button. Is it something to do with my selectors?
let quotes = ['The greatest glory in living lies not in never falling, but in rising every time we fall.', 'The way to get started is to quit talking and begin doing.', 'If life were predictable it would cease to be life, and be without flavor.', 'Life is what happens when youre busy making other plans.', 'Spread love everywhere you go. Let no one ever come to you without leaving happier.'];
let author = ['Nelson Mandela', 'Walt Disney', 'Eleanor Roosevelt', 'John Lennon', 'Mother Teresa'];
const quoteId = document.querySelector('.quote');
const authorId = document.querySelector('.source');
const btn = document.getElementById('loadQuote');
btn.addEventListener('click', function() {
quote.textContent = quotes[randomNum()];
source.textContent = author[randomNum()];
});
function randomNum() {
Math.floor(Math.random() * quotes.length)
};
<div id="quote-box">
<p >You can do anything but not everything</p>
<p >David Allen<span >Making It All Work</span><span >2009</span></p>
</div>
<button id="loadQuote">Show another quote</button>
</div>
CodePudding user response:
There are different mistakes:
In named function you sould explicitly write "return" what you want to be returned by the functions,
Assuming "quote" and "author" are paired by their position, you should use a common "randNum" in the function passed in the event listener,
Other type error fixed.
let quotes = [
"The greatest glory in living lies not in never falling, but in rising every time we fall.",
"The way to get started is to quit talking and begin doing.",
"If life were predictable it would cease to be life, and be without flavor.",
"Life is what happens when youre busy making other plans.",
"Spread love everywhere you go. Let no one ever come to you without leaving happier.",
];
let author = [
"Nelson Mandela",
"Walt Disney",
"Eleanor Roosevelt",
"John Lennon",
"Mother Teresa",
];
const quoteId = document.querySelector(".quote");
const authorId = document.querySelector(".source");
const btn = document.getElementById("loadQuote");
btn.addEventListener("click", function () {
let randNum = randomNum();
quoteId.textContent = quotes[randNum];
authorId.textContent = author[randNum];
});
function randomNum() {
return Math.floor(Math.random() * quotes.length);
}
CodePudding user response:
I've had this issue many times in the past. You can do one of two things:
You can change the btn.addEventListener('click', ...)
to btn.onclick = function() { ... }
Or, you can change btn.addEventListener('click', ...)
to btn.addEventListener('onclick')
This happens because the 'click' function is run since it is a query of the button element. Imagine it like it is inside the button element where you would do <button onclick="myFunction()"></button>
.