Below is the code I currently have. The problem I'm having is that where the quotes are supposed to be shown on the web page, it is just saying "undefined". I honestly am not sure where the problem is coming from.
var randomQ = randomInt(0, 10);
function randomInt(lowest, size) {
Math.floor(Math.random() * size) + lowest;
return randomQ;
}
var quoteElem = document.getElementsByTagName("quote")[0];
quoteElem.innerHTML = getQuote(randomQ);
function getQuote(n) {
var quotes = [
"It is a truth universally acknowledged, that a single man in possession of a good fortune, must be in want of a wife.",
"I hate to hear you talk about all women as if they were fine ladies instead of rational creatures. None of us want to be in calm waters all our lives.",
"Silly things do cease to be silly if they are done by sensible people in an impudent way.",
"Give a girl an education and introduce her properly into the world, and ten to one but she has the means of settling well, without further expense to anybody.",
"Life seems but a quick succession of busy nothings.",
"Our scars make us know that our past was for real.",
"I cannot speak well enough to be unintelligible.",
"One cannot be always laughing at a man without now and then stumbling on something witty.",
"Men were put into the world to teach women the law of compromise.",
"The person, be it gentlemen or lady, who has not pleasure in a good novel, must be intolerably stupid."
];
return quotes[n];
}
You should learn to read your errors. undefined what?
"message": "Uncaught TypeError: Cannot set property 'innerHTML'
This means you're trying to set the innerHTML of an element that can't be found/doesn't exist.
var quoteElem = document.getElementsByTagName("quote")[0];
In HTML, there is no element tag called 'quote'. Perhaps you mean an element with an ID of 'quote' ?
Secondly, your function called randomInt() wasn't returning the random number you generated, but rather some undefined variable called 'randomQ'
var randomQ = randomInt(0, 10);
function randomInt(lowest, size) {
//Return the actual value instead
return Math.floor(Math.random() * size) + lowest;
//return randomQ <-- what is this? This is what is undefined
}
var quoteElem = document.getElementById("quote");
quoteElem.innerHTML = getQuote(randomQ);
function getQuote(n) {
var quotes = [
"It is a truth universally acknowledged, that a single man in possession of a good fortune, must be in want of a wife.",
"I hate to hear you talk about all women as if they were fine ladies instead of rational creatures. None of us want to be in calm waters all our lives.",
"Silly things do cease to be silly if they are done by sensible people in an impudent way.",
"Give a girl an education and introduce her properly into the world, and ten to one but she has the means of settling well, without further expense to anybody.",
"Life seems but a quick succession of busy nothings.",
"Our scars make us know that our past was for real.",
"I cannot speak well enough to be unintelligible.",
"One cannot be always laughing at a man without now and then stumbling on something witty.",
"Men were put into the world to teach women the law of compromise.",
"The person, be it gentlemen or lady, who has not pleasure in a good novel, must be intolerably stupid."
];
return quotes[n];
}
<div id="quote"></div>
Related
Setting a background color "yellow" for words in a paragraph that has more than 8 characters.
I tried the below JavaScript code but it shows Cannot set properties of undefined (setting 'color')
const a=document.querySelector("p");
a.innerHTML=
a.innerText.split(" ")
.map(
function(word){
if (word.length>8){
word.style.color="yellow";
}
else{
return word;
}
}
)
.join(" ");
<h1>Heading</h1>
<!-- this is the paragraph I used-->
<p>Hey, you're not permitted in there. It's restricted. You'll be deactivated for sure.. Don't call me a mindless philosopher, you overweight glob of grease! Now come out before somebody sees you. Secret mission? What plans? What are you talking about? I'm not getting in there! I'm going to regret this. There goes another one. Hold your fire. There are no life forms. It must have been short-circuited. That's funny, the damage doesn't look as bad from out here. Are you sure this things safe?
Close up formation. You'd better let her loose. Almost there! I can't hold them! It's away! It's a hit! Negative. Negative! It didn't go in. It just impacted on the surface. Red Leader, we're right above you. Turn to point... oh-five, we'll cover for you. Stay there... I just lost my starboard engine. Get set to make your attack run.
The Death Star plans are not in the main computer. Where are those transmissions you intercepted? What have you done with those plans? We intercepted no transmissions. Aaah....This is a consular ship. Were on a diplomatic mission. If this is a consular ship...were is the Ambassador? Commander, tear this ship apart until you've found those plans and bring me the Ambassador. I want her alive! There she is! Set for stun! She'll be all right. Inform Lord Vader we have a prisoner.
What a piece of junk. She'll make point five beyond the speed of light. She may not look like much, but she's got it where it counts, kid. I've added some special modifications myself. We're a little rushed, so if you'll hurry aboard we'll get out of here. Hello, sir. Which way? All right, men. Load your weapons! Stop that ship! Blast 'em! Chewie, get us out of here! Oh, my. I'd forgotten how much I hate space travel.
Run, Luke! Run!</p>
May be we can try with just having innerHTML modified with returning span elements.
<script>
const a=document.querySelector("p");
const text = a.innerHTML.split(" ").map(function(word) {
if(word.length > 8) {
return `<span style="color: yellow;">${word}</span>`
} else {
return `<span>${word}</span>`
}
}).join(" ")
a.innerHTML= text
</script>
const a=document.querySelector("p");
const words=a.innerHTML.split(" ");
a.innerHTML=words.map((item)=>{
if(item.length>8) {
return `<span style="background:yellow">${item}</span>`
} else {
return item;
}
}).join(" ");
Simple one(highlight all word)
var wordList = document.getElementById('para').innerText.split(" ");
for (let n = 0; n < wordList.length; n++) {
wordList[n] = `<span class="word">${wordList[n]}</span>`//set class for words,and make it a span
}
document.getElementById('para').innerHTML=wordList.join(" ");//set back
.word {
background-color: yellow;
}
<h1>Heading</h1>
<p id='para'>Hey, you're not permitted in there. It's restricted. You'll be deactivated for sure.. Don't call me a mindless philosopher, you overweight glob of grease! Now come out before somebody sees you. Secret mission? What plans? What are you talking about? I'm not getting in there! I'm going to regret this. There goes another one. Hold your fire. There are no life forms. It must have been short-circuited. That's funny, the damage doesn't look as bad from out here. Are you sure this things safe?
Close up formation. You'd better let her loose. Almost there! I can't hold them! It's away! It's a hit! Negative. Negative! It didn't go in. It just impacted on the surface. Red Leader, we're right above you. Turn to point... oh-five, we'll cover for you. Stay there... I just lost my starboard engine. Get set to make your attack run.
The Death Star plans are not in the main computer. Where are those transmissions you intercepted? What have you done with those plans? We intercepted no transmissions. Aaah....This is a consular ship. Were on a diplomatic mission. If this is a consular ship...were is the Ambassador? Commander, tear this ship apart until you've found those plans and bring me the Ambassador. I want her alive! There she is! Set for stun! She'll be all right. Inform Lord Vader we have a prisoner.
What a piece of junk. She'll make point five beyond the speed of light. She may not look like much, but she's got it where it counts, kid. I've added some special modifications myself. We're a little rushed, so if you'll hurry aboard we'll get out of here. Hello, sir. Which way? All right, men. Load your weapons! Stop that ship! Blast 'em! Chewie, get us out of here! Oh, my. I'd forgotten how much I hate space travel.
Run, Luke! Run!</p>
Complex (highlight specific word with specific style)
const SpecialWords = [
"It's",
"you"//style word
];
const WordColors = [
"word",
"word2"//style class name
];
var wordList = document.getElementById('para').innerText.split(" ");
for (let n = 0; n < SpecialWords.length; n++) {
var res = replaceAll(wordList,SpecialWords[n],`<span class="${WordColors[n]}">${SpecialWords[n]}</span>`).join(" ");//style adding
}
document.getElementById('para').innerHTML=res;//set back
function replaceAll(array, find, replace) {
var arr = array;
for (let i = 0; i < arr.length; i++) {
if (arr[i] == find)
arr[i] = replace;
}
return (arr);
}
.word {
background-color: yellow;
}
.word2 {
background-color: lightgreen;
}
<h1>Heading</h1>
<p id='para'>Hey, you're not permitted in there. It's restricted. You'll be deactivated for sure.. Don't call me a mindless philosopher, you overweight glob of grease! Now come out before somebody sees you. Secret mission? What plans? What are you talking about? I'm not getting in there! I'm going to regret this. There goes another one. Hold your fire. There are no life forms. It must have been short-circuited. That's funny, the damage doesn't look as bad from out here. Are you sure this things safe?
Close up formation. You'd better let her loose. Almost there! I can't hold them! It's away! It's a hit! Negative. Negative! It didn't go in. It just impacted on the surface. Red Leader, we're right above you. Turn to point... oh-five, we'll cover for you. Stay there... I just lost my starboard engine. Get set to make your attack run.
The Death Star plans are not in the main computer. Where are those transmissions you intercepted? What have you done with those plans? We intercepted no transmissions. Aaah....This is a consular ship. Were on a diplomatic mission. If this is a consular ship...were is the Ambassador? Commander, tear this ship apart until you've found those plans and bring me the Ambassador. I want her alive! There she is! Set for stun! She'll be all right. Inform Lord Vader we have a prisoner.
What a piece of junk. She'll make point five beyond the speed of light. She may not look like much, but she's got it where it counts, kid. I've added some special modifications myself. We're a little rushed, so if you'll hurry aboard we'll get out of here. Hello, sir. Which way? All right, men. Load your weapons! Stop that ship! Blast 'em! Chewie, get us out of here! Oh, my. I'd forgotten how much I hate space travel.
Run, Luke! Run!</p>
we have to use spans(javascript will make words to spans)
see my answer here for reference
For this you have to create span elements because you need to add background color on each word. Here is a snippet that inserts appends span tag if the the word has more than 8 characters. If the words have less than 8, it will be inserted as a text.
const a=document.querySelector("p");
const b = document.createElement("span");
b.style.background = "yellow";
const words = a.innerHTML.split(" ");
a.innerHTML = "";
for(let i=0; i<words.length;i++){
if(words[i].length>8){
b.innerText = words[i];
b.innerText += " ";
a.appendChild(b);
}
else{
a.innerHTML += words[i];
a.innerHTML += " ";
}
}
<h1>Heading</h1>
<!-- this is the paragraph I used-->
<p>Hey, you're not permitted in there. It's restricted. You'll be deactivated for sure.. Don't call me a mindless philosopher, you overweight glob of grease! Now come out before somebody sees you. Secret mission? What plans? What are you talking about? I'm not getting in there! I'm going to regret this. There goes another one. Hold your fire. There are no life forms. It must have been short-circuited. That's funny, the damage doesn't look as bad from out here. Are you sure this things safe?
Close up formation. You'd better let her loose. Almost there! I can't hold them! It's away! It's a hit! Negative. Negative! It didn't go in. It just impacted on the surface. Red Leader, we're right above you. Turn to point... oh-five, we'll cover for you. Stay there... I just lost my starboard engine. Get set to make your attack run.
The Death Star plans are not in the main computer. Where are those transmissions you intercepted? What have you done with those plans? We intercepted no transmissions. Aaah....This is a consular ship. Were on a diplomatic mission. If this is a consular ship...were is the Ambassador? Commander, tear this ship apart until you've found those plans and bring me the Ambassador. I want her alive! There she is! Set for stun! She'll be all right. Inform Lord Vader we have a prisoner.
What a piece of junk. She'll make point five beyond the speed of light. She may not look like much, but she's got it where it counts, kid. I've added some special modifications myself. We're a little rushed, so if you'll hurry aboard we'll get out of here. Hello, sir. Which way? All right, men. Load your weapons! Stop that ship! Blast 'em! Chewie, get us out of here! Oh, my. I'd forgotten how much I hate space travel.
Run, Luke! Run!</p>
filter function is Appropriate for your issue:
const element = document.querySelector("p");
const array = element.innerText.split(" ");
const eightCharacter = array.filter(function(word) {
return word.length > 8;
});
const filteredWord = array.map(function(word) {
if (eightCharacter.indexOf(word) != -1) {
return '<span class="word">' + word + '</span>';
} else {
return word;
}
});
element.innerHTML = filteredWord.join(' ');
.word {
color: yellow;
}
<h1>Heading</h1>
<!-- this is the paragraph I used-->
<p>Hey, you're not permitted in there. It's restricted. You'll be deactivated for sure.. Don't call me a mindless philosopher, you overweight glob of grease! Now come out before somebody sees you. Secret mission? What plans? What are you talking about? I'm
not getting in there! I'm going to regret this. There goes another one. Hold your fire. There are no life forms. It must have been short-circuited. That's funny, the damage doesn't look as bad from out here. Are you sure this things safe? Close up formation.
You'd better let her loose. Almost there! I can't hold them! It's away! It's a hit! Negative. Negative! It didn't go in. It just impacted on the surface. Red Leader, we're right above you. Turn to point... oh-five, we'll cover for you. Stay there...
I just lost my starboard engine. Get set to make your attack run. The Death Star plans are not in the main computer. Where are those transmissions you intercepted? What have you done with those plans? We intercepted no transmissions. Aaah....This is
a consular ship. Were on a diplomatic mission. If this is a consular ship...were is the Ambassador? Commander, tear this ship apart until you've found those plans and bring me the Ambassador. I want her alive! There she is! Set for stun! She'll be all
right. Inform Lord Vader we have a prisoner. What a piece of junk. She'll make point five beyond the speed of light. She may not look like much, but she's got it where it counts, kid. I've added some special modifications myself. We're a little rushed,
so if you'll hurry aboard we'll get out of here. Hello, sir. Which way? All right, men. Load your weapons! Stop that ship! Blast 'em! Chewie, get us out of here! Oh, my. I'd forgotten how much I hate space travel. Run, Luke! Run!</p>
Note to: Using arrays to change color of certain words in an input box
I am working in infinite load, when i am first scroll to the bottom, the next data load to page. But after the next data load to page, it makes another data to be load and it load when I'm not continue to scroll again.
for example, when i first scroll to bottom the URL change to tes.html?page=1, but after a few seconds it will change to tes.html?page=2, tes.html?page=3 and so on. How to make page number change in URL and load data based on page number when scroll again?
Heres' the code
$(document).ready(function () {
let articleText = document.querySelector(".article_ct .text");
let currentPage = 1;
let totalPage = 5;
function loadData(currentPage) {
fetch("index.json")
.then((response) => response.json())
.then((result) => {
let text = document.createElement("p");
text.style.marginBottom = "100px";
text.innerText = result[currentPage].text;
articleText.append(text);
history.pushState(null, null, `tes.html?page=${currentPage}`);
})
.catch((error) => console.log(error));
return true;
}
// LOAD DATA PERTAMA
fetch("index.json")
.then((response) => response.json())
.then((result) => {
let text = document.createElement("p");
text.style.marginBottom = "100px";
text.innerText = result[0].text;
articleText.append(text);
})
.catch((error) => console.log(error));
$(window).scroll(function () {
if (
$(this).scrollTop() >
articleText.offsetHeight + articleText.offsetTop + 100
) {
if (currentPage <= totalPage) {
$(".loader").css("display", "block");
loadData(currentPage);
currentPage++;
} else {
$(".loader").css("display", "none");
}
}
// if($(this).scrollTop() > (articleText.offsetTop + articleText.offsetHeight)) {
// console.log('tes')
// }
});
});
Heres the json data file
[
{
"text": "The box sat on the desk next to the computer. It had arrived earlier in the day and business had interrupted her opening it earlier. She didn't who had sent it and briefly wondered who it might have been. As she began to unwrap it, she had no idea that opening it would completely change her life. If you can imagine a furry humanoid seven feet tall, with the face of an intelligent gorilla and the braincase of a man, you'll have a rough idea of what they looked like -- except for their teeth. The canines would have fitted better in the face of a tiger, and showed at the corners of their wide, thin-lipped mouths, giving them an expression of ferocity. There were only two ways to get out of this mess if they all worked together. The problem was that neither was all that appealing. One would likely cause everyone a huge amount of physical pain while the other would likely end up with everyone in jail. In Sam's mind, there was only one thing to do. He threw everyone else under the bus and he secretly sprinted away leaving the others to take the fall without him."
},
{
"text": "April seriously wondered about her sleeping partner choices. She looked at her bed and what a mess it had become. How did she get to the point in her life where she had two dogs, three cats, and a raccoon sleeping with her every night? She patiently waited for his number to be called. She had no desire to be there, but her mom had insisted that she go. She's resisted at first, but over time she realized it was simply easier to appease her and go. Mom tended to be that way. She would keep insisting until you wore down and did what she wanted. So, here she sat, patiently waiting for her number to be called. Stranded. Yes, she was now the first person ever to land on Venus, but that was of little consequence. Her name would be read by millions in school as the first to land here, but that celebrity would never actually be seen by her. She looked at the control panel and knew there was nothing that would ever get it back into working order. She was the first and it was not clear th is would also be her last."
},
{
"text": "Should he write it down? That was the question running through his mind. He couldn't believe what had just happened and he knew nobody else would believe him as well. Even if he documented what had happened by writing it down, he still didn't believe anyone would still believe it. So the question remained. Was it be worth it to actually write it down? I inadvertently went to See's Candy last week (I was in the mall looking for phone repair), and as it turns out, See's Candy now charges a dollar -- a full dollar -- for even the simplest of their wee confection offerings. I bought two chocolate lollipops and two chocolate-caramel-almond things. The total cost was four-something. I mean, the candies were tasty and all, but let's be real: A Snickers bar is fifty cents. After this dollar-per-candy revelation, I may not find myself wandering dreamily back into a See's Candy any time soon."
},
{
"text": "It was a scrape that he hardly noticed. Sure, there was a bit of blood but it was minor compared to most of the other cuts and bruises he acquired on his adventures. There was no way he could know that the rock that produced the cut had alien genetic material on it that was now racing through his bloodstream. He felt perfectly normal and continued his adventure with no knowledge of what was about to happen to him. He sat across from her trying to imagine it was the first time. It wasn't. Had it been a hundred? It quite possibly could have been. Two hundred? Probably not. His mind wandered until he caught himself and again tried to imagine it was the first time. Benny was tired. Not the normal every day tired from a hard day o work. The exhausted type of tired where you're surprised your body can even move. All he wanted to do was sit in front of the TV, put his feet up on the coffee table, and drink a beer. The only issue was that he had forgotten where he lived."
},
{
"text": "It was a simple tip of the hat. Grace didn't think that anyone else besides her had even noticed it. It wasn't anything that the average person would notice, let alone remember at the end of the day. That's why it seemed so unbelievable that this little gesture would ultimately change the course of the world. She was aware that things could go wrong. In fact, she had trained her entire life in anticipation that things would go wrong one day. She had quiet confidence as she started to see that this was the day that all her training would be worthwhile and useful. At this point, she had no idea just how wrong everything would go that day. I checked in for the night at Out O The Way motel. What a bad choice that was. First I took a shower and a spider crawled out of the drain. Next, the towel rack fell down when I reached for the one small bath towel. This allowed the towel to fall halfway into the toilet. I tried to watch a movie, but the remote control was sticky and wouldn’t stop scrolling through the channels. I gave up for the night and crawled into bed. I stretched out my leg and felt something furry by my foot. Filled with fear, I reached down and to my surprise, I pulled out a raccoon skin pair of underwear. After my initial relief that it wasn’t alive, the image of a fat, ugly businessman wearing raccoon skin briefs filled my brain. I jumped out of the bed, threw my t"
}
]
function Emotions(var quote) {
var Happy = [
"happiness is when what you think, what you say, and what you do are in harmony.",
"There is only one happiness in this life, to love and be loved.",
"Be happy for this moment. This moment is your life.",
"Happiness lies in the joy of achievement and the thrill of creative effort.",
"Be kind whenever possible. It is always possible.",
"Adopt the pace of nature: Her secret is patience.",
"Spread love everywhere you go. Let no one ever come to you without leaving happier.",
"Resolve to keep happy, and your joy and you shall form an invincible host against difficulties.",
"The present moment is filled with joy and happiness. If you are attentive, you will see it.",
"Action may not always bring happiness, but there is no happiness without action."];
var Sad = [
"It’s sad when you realize you aren’t as important to someone as you thought you were",
"What do you do when the only one who can make you stop crying is the one who made you cry",
"I smile not for that I am happy, but sometimes I smile to hide sadness.",
"Sometimes, crying is the only way your eyes speak when your mouth can’t explain how broken your heart is.",
"The ones that you love the most are usually the ones that hurt you the most! ",
"Ignore me. I don’t care. I’m used to it anyways. I’m invisible.",
"I’m not okay, I’m just good at pretending I am.",
"Nothings worse, is to see them two together, knowing I will never have him again.",
"It hurts the worst when the person that made you feel so special yesterday, makes you feel so unwanted today.",
"Sometimes it’s better to be Alone…Nobody can hurt you."
];
var Anger = ["I shall allow no man to belittle my soul by making me hate him",
"Anger and intolerance are the enemies of correct understanding.",
"When anger rises, think of the consequences.",
"For every minute you remain angry, you give up sixty seconds of peace of mind.",
"Never go to bed mad. Stay up and fight.",
"Angry people are not always wise",
"The best fighter is never angry",
"Speak when you are angry and you will make the best speech you will ever regret.",
"Anger, resentment and jealousy doesn't change the heart of others-- it only changes yours.",
"A heart filled with anger has no room for love"]
var arr1 = { Happy, Sad, Anger};
const randomQuote = arr1.quote[Math.floor(Math.random() * quote.length )];
return console.log(randomQuote);
}
Emotions(`Fear`);
this line not working in extracting the random data from preferrred objects.
// const randomQuote = arr1.quote[Math.floor(Math.random() * quote.length )];
What's the problem?
function Emotions(genre) {
// Abstracting this as a separate function
const randomNum = max => Math.floor(Math.random() * max)
const arr1 = { Happy, Sad, Anger}; // Don't use var
// Get the Genre
const selectedGenre = arr1[genre]
// Then random Quote from it
const randomQuote = selectedGenre[randomNum(randomGenre.length)];
// Returning as console.log() is not good practice
// it will affect the function's reusability
return randomQuote;
}
console.log(Emotions('Happy'))
I am trying to create an HTML page that outputs random Mark Twain quotes. I have the function and quotes array set up in a separate (linked) Javascript file. For whatever reason, I can't get the output to show up on the HTML document.
*Edit to add: My apologies for not doing better research & finding that case sensitivity matters in cases like these. I'm a newbie :)
Here is my Javascript code.
// Quotes
var quotes = [
["The size of a misfortune is not determinable by an outsider's measurement of it but only by the measurements applied to it by the person specially affected by it. The king's lost crown is a vast matter to the king but of no consequence to the child. The lost toy is a great matter to the child but in the king's eyes it is not a thing to break the heart about."],
["Trivial Americans go to Paris when they die."],
["There isn't time -- so brief is life -- for bickerings, apologies, heartburnings, callings to account. There is only time for loving -- & but an instant, so to speak, for that."],
["Thunder is good, thunder is impressive; but it is lightning that does the work."],
["Everyone is a moon, and has a dark side which he never shows to anybody."]
];
// Generate a random number from the array
function random_item(quotes) {
return quotes[math.floor(math.random()*quotes.length)];
}
Here is my HTML code with the output that isn't working. I'm not including the full thing because this is the only relevant part.
<div id="quotes">
<script>
document.write(random_item(quotes));
</script>
</div>
If it were working, each time the page is visited/refreshed, one of the quotes should display at random. They won't show up at all though.
you have a typo with the Math object.
And consider avoiding putting script inside div
// Quotes
var quotes = [
["The size of a misfortune is not determinable by an outsider's measurement of it but only by the measurements applied to it by the person specially affected by it. The king's lost crown is a vast matter to the king but of no consequence to the child. The lost toy is a great matter to the child but in the king's eyes it is not a thing to break the heart about."],
["Trivial Americans go to Paris when they die."],
["There isn't time -- so brief is life -- for bickerings, apologies, heartburnings, callings to account. There is only time for loving -- & but an instant, so to speak, for that."],
["Thunder is good, thunder is impressive; but it is lightning that does the work."],
["Everyone is a moon, and has a dark side which he never shows to anybody."]
];
// Generate a random number from the array
function random_item(quotes) {
return quotes[Math.floor(Math.random()*quotes.length)];
}
document.querySelector('#quotes').innerText = random_item(quotes); // use instead of document.write
<div id="quotes">
</div>
I have a problem with my .onclick function not executing the function specified in my script file. Here's my code:
JAVASCRIPT:
var quotes = [
["“If you are distressed by anything external, the pain is not due to the thing itself, but to your estimate of it; and this you have the power to revoke at any moment.”", "Marcus Aurelius"],["“The average man is a conformist, accepting miseries and disasters with the stoicism of a cow standing in the rain.”", "Colin Wilson"],
["“Never let the future disturb you. You will meet it, if you have to, with the same weapons of reason which today arm you against the present.”", "Marcus Aurelius"],
["“Warriors should suffer their pain silently.”","Erin Hunter"],
["“Complaining does not work as a strategy. We all have finite time and energy. Any time we spend whining is unlikely to help us achieve our goals. And it won't make us happier.”", "Randy Pausch"],
["“It is the power of the mind to be unconquerable.”", "Seneca"],
["“How do you defeat terrorism? Don’t be terrorized.”", "Salman Rushdie"],
["“It is not the man who has too little that is poor, but the one who hankers after more.”", "Seneca"],
["“What really frightens and dismays us is not external events themselves, but the way in which we think about them. It is not things that disturb us, but our interpretation of their significance.”", "Epictetus"],
["“For death remembered should be like a mirror, who tells us life’s but breath, to trust it error.”", "Shakespeare"],
["“No one saves us but ourselves. No one can and no one may. We ourselves must walk the path.”", "Buddha"],
["“You only lose what you cling to.”", "Buddha"],
["“Man suffers only because he takes seriously what the gods made for fun.”", "Alan W. Watts"],
["“If there is any religion that could respond to the needs of modern science, it would be Buddhism.”", "Albert Einstein"],
["“We are not going in circles, we are going upwards. The path is a spiral; we have already climbed many steps.”", "Hermann Hesse"],
["“Treat every moment as your last. It is not preparation for something else.”", "Shunryu Suzuki"],
["“Better than a thousand hollow words is one word that brings peace.”", "Buddha"],
["“Life is painful. It has thorns, like the stem of a rose. Culture and art are the roses that bloom on the stem. The flower is yourself, your humanity. Art is the liberation of the humanity inside yourself.”", "Daisaku Ikeda"],
["“Learning to let go should be learned before learning to get. Life should be touched, not strangled. You’ve got to relax, let it happen at times, and at others move forward with it.”", "Ray Bradbury"]
];
var randomInt = Math.floor((Math.random() * quotes.length) + 1);
// Generate random number
// Get number's position from array
var aQuote = function() {
return quotes[randomInt][0] + "";
};
var aQuoteAuthor = function() {
return quotes[randomInt][1] + "";
};
// Change textblock into quote + author
// Display quote on page
// Display author on page
function changeButton() {
document.getElementById('quote').innerHTML = aQuote();
document.getElementById('quoteAuthor').innerHTML = aQuoteAuthor();
};
// Register button press
document.getElementById('aButton').onclick = changeButton();
And this is my html:
<div class="container">
<div class="row">
<div class="u-full-width">
<div class="quotediv">
<h5 id="quote" class="text-primary-color">“Imagine smiling after a slap in the face. Then think of doing it twenty-four hours a day.”</h5>
<p id="quoteAuthor" class="light-primary-color">Markus Zusak<p>
<button id="aButton" type="button button-primary" class="primary-text-color"> NEW QUOTE</button>
</div>
</div>
</div>
</div>
<script src ="scripts/script.js"></script>
The first weird thing is that the function changeButton() gets invoked automatically on page load without a function call. So on every page load there's a new quote generated and displayed. The second weird thing is that the button itself does not generate and change the quote via the function changeButton().
Could anyone point me in the right direction?
P.S. I'm a coding newbie. This is my first question on SO. I tried to follow the guidelines for specificity but if you have any tips or comments on my question formulation, please let me know! :)
The problem is that you are executing the function and assigning the return value to onclick.
document.getElementById('aButton').onclick = changeButton();
You should be assigning the function itself to onclick like so (Note it doesnt have "()" at the end)
document.getElementById('aButton').onclick = changeButton;
Even better would be to use addEventListener like so
document.getElementById('aButton').addEventListener('click', changeButton);
Try to do it like that:
document.getElementById('aButton').onclick = changeButton
what you were doing is binding event and simultaneously executing it.
document.getElementById('aButton').onclick = changeButton
function changeButton() {
console.log("yes");
}
<button id="aButton">
Button
</button>
You can call the onClick listener using
document.getElementById('aButton').addEventListener("click", changeButton);
Using:
document.getElementById('aButton').onclick = changeButton();
You just assign the return value of the function rather than assign the function to the click event! This line:
document.getElementById('aButton').onclick = changeButton;
Actually assigns the function to the click event (note, no brackets so it isn't executed, it's assigned as a variable).
function changeButton() {
alert("Hello")
}
document.getElementById('aButton').addEventListener("click", changeButton);
<button id="aButton">Click Me</button>
move your script to head section it will work fine.
<!DOCTYPE html>
<html>
<head>
<script>
var quotes = [
["“If you are distressed by anything external, the pain is not due to the thing itself, but to your estimate of it; and this you have the power to revoke at any moment.”", "Marcus Aurelius"],["“The average man is a conformist, accepting miseries and disasters with the stoicism of a cow standing in the rain.”", "Colin Wilson"],
["“Never let the future disturb you. You will meet it, if you have to, with the same weapons of reason which today arm you against the present.”", "Marcus Aurelius"],
["“Warriors should suffer their pain silently.”","Erin Hunter"],
["“Complaining does not work as a strategy. We all have finite time and energy. Any time we spend whining is unlikely to help us achieve our goals. And it won't make us happier.”", "Randy Pausch"],
["“It is the power of the mind to be unconquerable.”", "Seneca"],
["“How do you defeat terrorism? Don’t be terrorized.”", "Salman Rushdie"],
["“It is not the man who has too little that is poor, but the one who hankers after more.”", "Seneca"],
["“What really frightens and dismays us is not external events themselves, but the way in which we think about them. It is not things that disturb us, but our interpretation of their significance.”", "Epictetus"],
["“For death remembered should be like a mirror, who tells us life’s but breath, to trust it error.”", "Shakespeare"],
["“No one saves us but ourselves. No one can and no one may. We ourselves must walk the path.”", "Buddha"],
["“You only lose what you cling to.”", "Buddha"],
["“Man suffers only because he takes seriously what the gods made for fun.”", "Alan W. Watts"],
["“If there is any religion that could respond to the needs of modern science, it would be Buddhism.”", "Albert Einstein"],
["“We are not going in circles, we are going upwards. The path is a spiral; we have already climbed many steps.”", "Hermann Hesse"],
["“Treat every moment as your last. It is not preparation for something else.”", "Shunryu Suzuki"],
["“Better than a thousand hollow words is one word that brings peace.”", "Buddha"],
["“Life is painful. It has thorns, like the stem of a rose. Culture and art are the roses that bloom on the stem. The flower is yourself, your humanity. Art is the liberation of the humanity inside yourself.”", "Daisaku Ikeda"],
["“Learning to let go should be learned before learning to get. Life should be touched, not strangled. You’ve got to relax, let it happen at times, and at others move forward with it.”", "Ray Bradbury"]
];
var randomInt = Math.floor((Math.random() * quotes.length) + 1);
// Generate random number
// Get number's position from array
var aQuote = function() {
return quotes[randomInt][0] + "";
};
var aQuoteAuthor = function() {
return quotes[randomInt][1] + "";
};
// Change textblock into quote + author
// Display quote on page
// Display author on page
function changeButton() {
alert();
document.getElementById('quote').innerHTML = aQuote();
document.getElementById('quoteAuthor').innerHTML = aQuoteAuthor();
};
</script>
</head>
<body>
<div class="container">
<div class="row">
<div class="u-full-width">
<div class="quotediv">
<h5 id="quote" class="text-primary-color">“Imagine smiling after a slap in the face. Then think of doing it twenty-four hours a day.”</h5>
<p id="quoteAuthor" class="light-primary-color">Markus Zusak<p>
<button id="aButton" type="button button-primary" class="primary-text-color"> NEW QUOTE</button>
</div>
</div>
</div>
</div>
</body>
</html>