Why isn't this Javascript function printing into my HTML document? - javascript

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>

Related

Infinite scroll make page number auto increase after first scroll

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"
}
]

Randomize numbers in a random order script

I have searched and although I see this addressed in Python and PHP, I don't see it using JS. This script randomizes order on refresh and I would like the numbers to be randomly generated as well as the order. The order part is already working, but I don't want it limited to numbers I input (150, 375 and 900 in this example). I'm going to have about 50 variables but I've just listed three to keep it short here.
I would also like to understand how to control the place values permitted, so I could have xx,xx,xx, etc./ xxx,xxx,xxx etc. and also how to state a range, so it could include xx,xxx,xxxx
Lastly I would be very keen to understand how to limit the generated numbers to meet certain profiles, like all tens (670,320,980,410,650), twenty-fives (375,925,400,850,175, etc.). This would be extremely helpful.
I'm sorry this is just beyond my ability, and I have tried and tried. I operate a school in India where I teach math, and we have had great success teaching number recognition and counting in English and Hindi using printed charts of numbers that fit different criteria like this, and I would like to adapt it to a mobile app, just to let you know why I'm asking. Many thanks.
var contents=new Array()
contents[0]='150'
contents[1]='375'
contents[2]='900'
*/
var spacing = "<br />"
var the_one
var z = 0
while (z<contents.length){
the_one=Math.floor(Math.random()*contents.length)
if (contents[the_one]!="_selected!"){
document.write(contents[the_one]+spacing)
contents[the_one]="_selected!"
z++
}
}

How to format a large variable of text into smaller variables in JavaScript?

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>

.onclick button not executing function

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>

java script text based game and objects

I am writing a text based game where I want users to be able to manipulate any item.
I want the user to be able to say, for example, "I throw the bottle of oil at the monster."
Now when this happens [throw] will be an action, [bottle of oil] is an inventory item with the property [contains oil], and the monster will be the nearest monster in the room unless specified further.
Code needs to analyze the various properties of all these things and then pick actions that cause those things to interact.
When i write the Game story code it will be like follows
*room.darkroom.1 "wake up" [...] everything appears blurry, the voice sounds strange as if echoing down a long tunnel. From what you can see you can tell [you are in a dark room] your vision blurs from white to dark. [pc is inside very dark room. Inside this room everything is hidden in darkness. The northern wall has a locked thick wooden door. the southern wall has a barrel full of oil containing a bottle of oil. In the eastern side of the room are 2 medium sized crates one crate contains flint and rusty dagger. In the western side of the room a [small window] */room.darkroom.1
The script will take all those words and apply properties to them randomizing certain elements that are left unstated. So if you then say "chair" it will go to the chair properties and randomly assign unstated properties. One property of chair will be material. If its not stated that its an oak chair then the script should pick from any of the material properties and assign them. This new chair will pick up a few properties and be saved for future reference on the database with all properties.
Another property would be an action. A chair would not necessarily have an action .. but it might break. The script needs to know if the chair is breakable. But I am thinking that could be nested into another property like [toughness].
Many things will have many of the same properties: chair, night stand, table would all be similar in many ways. But they would also have different outcomes depending on the actions applied to them.
How do I specify for instance when "broken" contains chair legs and scrap material? The chair legs and the scrap material would both need to inherit the properties of the chair that was destroyed, such as oak / flammable / breakable. Obviously, as stated before, it might not have to inherit flammable or breakable if oak is the part that holds that value.
I want to make it easy to access the array that stores properties and that might include a script that effects behavior and descriptions of things.
I started to just create a keyed array which would be looped through... But now I am thinking that I should utilize the object based element of JavaScript.
Here is what i have started to do but I stopped right away:
var language = {
// key currentmodifyers possible modifyers action/condition description of item
item: ";medium,material;;its a thing thats not a person",
chair: "item,chair_Legs;;pile_of.#scraps.collection.chairlegx3/broken,#[chair ]scraps/destroyed; and someone could sit on it. ",
chair_leg:"item,blunt,light,"
}
I have so many definitions to write so it would be a shame to start writing it all and then have to do it over when I discover the best way.
I am looking at various ways to build objects in JavaScript, but would like the best way from someone experienced.
Understanding the complexity of my problem, what is the best way to store and apply properties?
There are actually two good thoughts in your question:
But now I am thinking that I should utilize the object based element of JavaScript.
You definitely need to use objects instead of arrays, the OOP ideas can be directly applied to your descriptions.
Some objects are composed of smaller parts (the "composition" in OOP) and some inherit properties of other objects (the "inheritance").
So you could have some base Item class which defines basic operations and properties for all objects (like they have different properties and can do some things).
Then you can add objects like StaticItem (will be base for chairs, night stands, etc) and LiveBeeing (monsters, etc).
And now you can actually create the Chair (pseudocode):
StaticItem extends Item
this.material = oak // oak is an object of OakMaterial
// is this static item flamable?
this.isFlamable = function() {
// we "redirect" flamability detection to the material
return this.material.flamable();
}
Chair extends Static
// break this chair!
this.break = function() {
// when it is broken we return a HeapOfCrap, it is a
// Static subclass which contains some sub-items
// In this case the heap contains 4 chair legs of the
// same material as the chair
return HeapOfCrap([
new ChairLeg(this.material), new ChairLeg(this.material),
new ChairLeg(this.material), new ChairLeg(this.material)
])
}
And so on, you need to plan you object structure carefully and there is a good field to apply some of the design patterns.
The example above is just what came in my mind immediately, while actual design should take much more time and thinking.
The second good thought in your question is about the huge amount of work:
I have so many definitions to write so it would be a shame to start writing it all and then have to do it over when I discover the best way.
You absolutely right here, would you select to use objects or arrays, or anything else - don't try to describe all your game right away.
Select few basic elements, like "Room", "Door", "Chair", "Monster", "Player" and try to code the minimal game with only these elements.
Play with the structure to find the good design and once you are sure it is good - go on and add more elements to the game.

Categories

Resources