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>
Related
I am currently trying to code this extremely basic text-based golf game for practice. There's no trigonometry to it, there's just a randomness to how hard you hit the ball, and then how many shots it takes to reach the hole. At the end, it will mark your score as "Birdie" or "Par" or whatever. I'm not at that endstage yet though.
So my logic for the program is, start() is called through an onclick HTML attribute, and then we run through things from there. Everything is embodied in start(). The game's intro text is displayed with some DOM innerHTML.
The idea is that once start() has been activated, you can click swing() and it will swing and update the value and therefore the current position.
But I don't get what problem it's having with this nested function and the onclick. The error it says it has is at index.html line 1. But also, line 1 of my index.HTML is . I don't even know what this other index file is.
image 1; images not necessary but might help explain what I'm talking about
In VS Code, the nested function says it never even gets called. Is it just reading the lines and exiting too fast? Should I use setInterval or something to keep it reading?
function start() {
let introText = "It is a beautiful sunny day on Golf Island. The cobalt waters are great. There is no wind. You stand at the tee and get ready to strike. There's only one hole to go.<br>"
document.getElementById("textarea").innerHTML += introText;
holeDistance = 350;
function swing() {
swingValue = Math.floor(Math.random() * 100);
currentValue = String(holeDistance - swingValue);
return document.getElementById("textarea").innerHTML += "Hole position: " + currentValue;
}
}
<button id="start" onclick="start()">Start game</button>
<div id="textarea">
<button onclick='swing()'>Swing</button>
</div>
Here's the Codepen.
There are a few issues:
your function is within another function
you assign values to variables that you have never declared before. A variable needs to be declared with var/let and can only be assigned afterward or at the same instance:
Issues to fix the game:
You declare a variable within the function of hole distance with 350. Every time you click the button you reset the variable to 350 and roll the dice on that 350. You need to move the variable outside of the function and subtract the randomize shooting distance from the hole distance:
let holeDistance = 350;
function start() {
let introText = "It is a beautiful sunny day on Golf Island. The cobalt waters are great. There is no wind. You stand at the tee and get ready to strike. There's only one hole to go.<br>"
document.getElementById("textarea").innerHTML += introText;
}
function swing() {
let swingValue = Math.floor(Math.random() * 100);
holeDistance = holeDistance - swingValue;
return document.getElementById("textarea").innerHTML += `Hole position: ${holeDistance}`;
}
<button id="start" onclick="start()">Start game</button>
<div id="textarea">
<button onclick='swing()'>Swing</button>
</div>
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'm using an API to pull data through to my application, and I'm pulling an object and it's property, however the property is just a large wall of text (shown below). The reason I can't use all the text is well...Because n
Is it possible to format this wall of text into smaller variables or such?
My current code is finding the length from the start of the text to the first fullstop, then creating a variable with that length to grab the first sentence.
//what it currently shows//
"Leonard Shelby is tracking down the man who raped and murdered his wife.
The difficulty of locating his wife's killer, however, is compounded by
the fact that he suffers from a rare, untreatable form of short-term
memory loss. Although he can recall details of life before his accident,
Leonard cannot remember what happened fifteen minutes ago, where he's
going, or why."
//What I want it to look like
"Leonard Shelby is tracking down the man who raped and murdered his wife.
The difficulty of locating his wife's killer, however, is compounded by
the fact that he suffers from a rare, untreatable form of short-term
memory loss.
Although he can recall details of life before his accident,
Leonard cannot remember what happened fifteen minutes ago, where he's
going, or why."
//my code//
var fullTvShowOverview = tvShow.overview;
var tvShowOverView = document.getElementById("tvshow-description");
var trimmedTvShowLength = fullTvShowOverview.indexOf(".");
var trimmedTvShowOverview = fullTvShowOverview.substring(0,
trimmedTvShowLength, ".");
trimmedTvShowOverview = trimmedTvShowOverview + ".";
tvShowOverView.textContent = trimmedTvShowOverview;
//my code produces: "Leonard Shelby is tracking down the man who raped and murdered his wife."
You will want to split the text string into an array, and then loop the array for your processing later. Here's a minimal example that is splitting on just .
let textStr ="This. is some. example. text.";
let results = textStr.split(". ");
console.log( results[1] )
you can place in an array and just use the indices to access each sentence
var fullTvShowOverview = "Leonard Shelby is tracking down the man who raped and murdered his wife.The difficulty of locating his wife's killer, however, is compounded by the fact that he suffers from a rare, untreatable form of short-term memory loss.Although he can recall details of life before his accident,Leonard cannot remember what happened fifteen minutes ago, where he's going, or why.";
var tvShowOverView = document.getElementById("tvshow-description");
var arraySplitByPeriod = fullTvShowOverview.split(".")
tvShowOverView.textContent = arraySplitByPeriod[0];
<div id="tvshow-description">
<div>
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>
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>