I am very new here and new to code. I not know anyone who can help me with this and have watched allot of youtube videos on how to try and solve my problem.
I am trying to loop through the array below using if then and else statements and the function cardCounter. I want the the items in the array to individually appear on the screen and then disappear one after the other. Right now my array just looks like lines of text on a screen when opened in my browser.
This is my code:
<script>
const calm1 = [];
calm1[0]= "Silence is the element in which great things fashion themselves
together. —Thomas Carlyle";
calm1[1]= "Take a deep breathe in and count to 7 seconds ";
calm1[2]= "Take a slow exhale out";
calm1[3]= "Self-care is not selfish. You cannot serve from an empty vessel.– Eleanor Brown";
calm1[4]= "Loneliness is a sign you are in desperate need of yourself.― Rupi Kaur,";
calm1[5]= "do not look for healingat the feet of thosewho broke you― Rupi Kaur,";
calm1[6]= "if you were born with the weakness to fall you were born with the strength to rise― Rupi Kaur";
calm1[7]= "you kill your future by mourning the past― R.H. Sin";
calm1[8]= "Our backs tell stories no books have the spine to carry― Rupi Kaur";
calm1[9]= "what is stronger than the human heart which shatters over and over and still lives― Rupi Kaur";
calm1[10]= "the world gives you so much pain and here you are making gold out of it- there is nothing purer than that― Rupi Kaur";
calm1[11]= "fall in love with your solitude― Rupi Kaur";
calm1[12]= "You do not just wake up and become the butterfly -Growth is a process.― Rupi Kaur";
document.getElementById("calm").innerHTML = calm1;
var words = document.getElementById('calm');
var text = -1;
function cardCounter () {
text++;
if (text<calm1.length) {
words = calm1[text];
}
else {
words = -1;
clearInterval(intervalTimer);
}
;}
var intervalTimer = setInterval(function(){cardCounter()},5000);
</script>
Welcome to StackOverflow and the wonderful world of JavaScript programming!
The If/Then/Else construct does not allow for iteration over a collection of objects, instead it only handles decision making. (IF some condition is met THEN do some action ELSE do something else)
What you are looking for is a loop of some kind, usually for this case you would use a FOR loop.
Your function would look something like this. I have changed some of the variable names to generalise them for others.
// Populate the statements as before
const statements = [];
// Get a reference to the HTML element you want to change
const calmElement = document.getElementById('calm');
// Create a timer function that will resolve after a specified number of milliseconds
const timer = ms => new Promise(res => setTimeout(res, ms))
// Define the function as asynchronous, meaning it will contain an awaited function call
async function cardCounter(delay) {
// Iterate over every statement in our list and do something with each one.
for(const statement of statements) {
// Now we have access to a statement, we can set the HTML element text property to be our next statement
calmElement.innerText = statement;
// Call the timer method we created above, this will halt execution for X milliseconds
await timer(delay);
}
}
Now you can call your function whenever you want to start the quotes running through
cardCounter(5000);
Credit to this stackoverflow post for setting up the timer.
It looks like you're trying to update some text in a div on a timer. While there are a number of ways to do this, here's one example.
const calm = [
"Silence is the element in which great things fashion themselves together. —Thomas Carlyle",
"Take a deep breathe in and count to 7 seconds ",
"Take a slow exhale out",
"Self-care is not selfish. You cannot serve from an empty vessel.– Eleanor Brown",
"Loneliness is a sign you are in desperate need of yourself.― Rupi Kaur,",
"do not look for healingat the feet of thosewho broke you― Rupi Kaur,",
"if you were born with the weakness to fall you were born with the strength to rise― Rupi Kaur",
"you kill your future by mourning the past― R.H. Sin",
"Our backs tell stories no books have the spine to carry― Rupi Kaur",
"what is stronger than the human heart which shatters over and over and still lives― Rupi Kaur",
"the world gives you so much pain and here you are making gold out of it- there is nothing purer than that― Rupi Kaur",
"fall in love with your solitude― Rupi Kaur",
"You do not just wake up and become the butterfly -Growth is a process.― Rupi Kaur"
];
// set the index to the first element
let index = 0;
// set the text in the calm div with the text at the index
function setText(index) {
document.getElementById("calm").innerText = calm[index];
}
// set initial text
setText(index);
// setup a timer to rotate text every 5 seconds
setInterval(() => {
// advance index, if index would roll off end of array, start over
if (index + 1 == calm.length) index = 0;
else ++index;
// set the text
setText(index);
}, 5000);
<html>
<body>
<div id="calm">
</div>
</body>
</html>
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'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>
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>