Javascript random quote generator NO REPEAT - javascript

Please refer to www.thisyeariwantto.com This is the js code I am using to display "random" quotes... but the problem I keep having is that the quotes on the array repeat themselves. I want the user to come in click and click without ever seeing the same quote twice. How can I achieve this? Thank you in advance.
function jargonator(){
$('#head').text("This year I want to...");
$('#tag').text("");
var fragments = shuffle(
["gym","Fall in love(cliche), be happy and work abroad","stop fighting with my boyfriend","to finish things, no matter how long they take or how silly they are", "I'LL FINISH EVERY THING I START !","adopt a Koala","write a book","make a million","grow a pair","get married","drink less live more","figure out where i buried her","Give my girlfriend a real orgasm","Read more books","Save more money","Lose weight","Redecorate","Take better photos so that I can gain more instagram followers","Stop it with the #selfies","Travel","Stop cheating on my husband","Sell old unwanted stuff on eBay","Do something for charity","Get new boobs","Spend more time with kids","Spend Less time on Facebook","Totally revamp my wardrobe","Try a new hairstyle... down there ;)","Have a threesome","Get a six-pack... of premium artisanal beer","Eat less chocolate","Socialise more in real life rather than Facebook","Drink less alcohol","Eat an entire bowl of Ben & Jerrys without feeling guilty", "Start my own business","Recommend this site to all my friends","Tell Susan I have feelings for her","Stop hitting my girlfriend","Do less cocaine","Quit smoking","Get a promotion","stop saying, 'Ooh, that feels nice' whenever the security guys frisk me at airports.","work with neglected children. (my own)","balance my checkbook. (on my nose).","Learn how to use Twitter","Stop sleeping with my brother’s fiancée","Have a better relationship with my parents","do less laundry and use more deodorant","assure my lawyer that I will never again show up drunk at a custody hearing.","start shaving my legs again","Run a half or full marathon","Call people more than text","Stop texting 'LOL'","Stop sexting my cousin", "Watch less reality TV","Stop treating my cat like a real person","Stop buying every iphone that comes out","Stop sleeping with my ex","Stop faking my orgasms","go to the beach more often","get penis reduction surgery so my girl lets me fuck her in the ass","start pretending i'm gay so I can get free drinks at the rainbow room","stop lying on my resume","Exclude McDonald's from my daily diet","Stop considering ketchup a vegetable","stop pretending I have friends","Make at least one REAL friend","Learn how to spell 'thru'... 'thrugh'... 'trhouh'.... fuck it.","Get into a fight so I can finally use my mma skills","stop watching mma so my girlfriend stops thinking I'm gay","Paint my balls blue so I always have an excuse for my gf to jerk me off","Tell Rebecca to fuck off, she is such a bitch","tell my son he is adopted, and his real name is not Kyle... it is Rodrigo.","Stop being a hipster because everyone is doing it","Stop being a hipster, thats so 2013","stop taking naked pictures in snapchat","Reduce, reuse, recycle :)","Graduate!","Be happy!","Take more pictures","Learn how to twerk","stick my tongue out and not feel dirty...like Miley","ride naked on a wrecking ball...with a hammer","make my first legal pornographic movie...with a hidden camera...","learn japanese curse words","star on a rap video as one of the hoes in the back","get my freak on...it's been off way too long...and people are talking","stop showing my boobs so I get more likes","make my momma proud","stop sleeping with my boss's daughter","wear condoms more often","tell him he is not the real dad...","Have intense lesbian sex in public places.","stop making new year's resolutions.","finally dunk.","stop doing Molly","Eat the still beating Heart of Jeff Gordan","get rich doing what i like","Do the splits!","speak up","finally open my own practice","meet a girl","be more positive","Stop being an intern and get a job.","travel to where the soul meets body.","get a tattoo","be fearless","stop curating, start creating", "continue to make my boyfriend happy to the best of my ability.","leave The City and start really living","become a mermaid","Quit 'Call me maybe'","Do my Irish penpal", "Have more bacon, have more sex","study quantum physics so I can RULE THE WORLD","stop biting my nails","drink quality instead of quantity","sleep completely naked in a middle of a peaceful forest","Take a shower with Ryan Gosling","break the circle of no-life", "BOOMSHAKALAKA!!!","Break the Internet", "go back to the future","play hide & seek with strangers on the internet","file a complaint to the Karma Police","NOT fall in love","Stop making a Morgan Freeman voice when talking about Nelson Mandela's death","Make my husband allergic to viagra... i am tired!! :)","cast a worldwide campaign to protest against animal abuse","drink over 20 Mezcal shots in a row","star in the next Star Wars movie","get inspired","stop thinking 'It'll be our year... I'm the only one being the Zombie","Try and see if I can live on wine and sushi... and nothing else","Prove Einstein was wrong","Buy a hammock and work from there","forget about Teen Spirit","find the second star to the right, and go straight on till morning","Leave Narcissus alone","write a novel","make the team","go to all my AA meetings","spit in the face of convention","Somewhere I've never been yet","learn a new recipe", "Paint!", "learn to meditate and at least take one weekend for myself to travel.",]
)
$('#c').click(function () {
change(1000);
});
function change(time){
$('#tag').animate({
opacity: 0
}, time, function () {
$('#tag').html(fragments.pop()).animate({
opacity: 1
}, time)
});
}
function shuffle(o) { //v1.0
for (var j, x, i = o.length; i; j = Math.floor(Math.random() * i), x = o[--i], o[i] = o[j], o[j] = x);
return o;
};
change(0);
}
I really need help. If you need to see any other code of any of the other files please let me know. thank you very much.

you can just poping it from array
for( var i=0;i<fragments.length;i++){
str += fragments[i].pop();
if(i <fragments.length-1){str+=stub;}
}
if you do so, then it remove quote and you never have dublicates.
and before doing this, you can sort array random, then you will have different quotes every time
something like this.

We cannot control the value returned by Math.random() as you expecting. However try this workaround, every time a value is generated add it to another array, say mylist
var fragments =[
["quote1", "quote2", "quote3","etc", ... ]
var selected;
var temp;
var str = "";
var stub = "";
for( var i=0;i<fragments.length;i++){
temp = fragments[i][Math.floor(Math.random()*fragments[i].length)];
while(selected.contains(temp)){
temp = fragments[i][Math.floor(Math.random()*fragments[i].length)];
}
selected.push(temp);
str += temp;
if(i <fragments.length-1){str+=stub;}
}
$('#tag').animate({opacity:0.9},1000).append(str);
}
Eventually at some time all randoms get generated after that clear mylist and continue. At least random wont repeat until all elements in your fragments get selected once.

Related

How to filter through an array for a user input in js?

I'm trying to build a random quote machine where a user can put in a topic word, an algorithm searches for that word within a list of quotes, makes a new list of quotes that contain that word, and then randomly returns a quote out of the filtered list. If there is no word in the list, it would return any random quote. I can't figure out how to make a filtered list in JavaScript. So far I've got:
<body>
<p id="quoteDisplay"></p>
</body>
<form>
<input type="text" id="topic" />
<button onclick="wiseQuote()">Quote</button>
</form>
<script type="text/javascript">
var quotes = [
"You've gotta dance like there's nobody watching, Love like you'll never be hurt, Sing like there's nobody listening, And live like it's heaven on earth. - William W. Purkey",
"You know you're in love when you can't fall asleep because reality is finally better than your dreams. - Elbert Hubbard",
"Being deeply loved by someone gives you strength, while loving someone deeply gives you courage - Lao Tzu",
"In three words I can sum up everything I've learned about life: it goes on. - Robert Frost",
"Everything in moderation, including moderation - Oscar Wilde",
"Life isn't about finding yourself. Life is about creating yourself. - George Bernard Shaw",
"Life is like riding a bicycle. To keep your balance, you must keep moving. - Albert Einstein",
"The truth is rarely pure and never simple. - Oscar Wilde",
"A lie can travel half way around the world while the truth is putting on its shoes.- Mark Twain",
"Perhaps one did not want to be loved so much as to be understood. - George Orwell",
"Facts do not cease to exist because they are ignored. - Aldous Huxley",
"Above all, don't lie to yourself. The man who lies to himself and listens to his own lie comes to a point that he cannot distinguish the truth within him, or around him, and so loses all respect for himself and for others. And having no respect he ceases to love. - Fyodor Dostoevsky",
"A thing is not necessarily true because a man dies for it. - Oscar Wilde",
"The unexamined life is not worth living. - Socrates"
]
if (topic != null){
filteredQuotes = quotes.filter(function(){
return ;
});
}
if (filteredQuotes.length) {
randomIndex = Math.floor(Math.random() * filteredQuotes.length);
filteredQuote = filteredQuotes[randomIndex];
} else {
randomIndex = Math.floor(Math.random() * quotes.length);
filteredQuote = quotes[randomIndex];
}
document.getElementById('quoteDisplay').innerHTML = filteredQuote;
}
</script>
This is the first project I'm building so I hope this code is not too much of a mess!! Thank you all so much in advance :)
You need to get value on input and in function of .filter() check that items has target text or not. Check it using .indexOf(). Then generate random number between 0 and length of filtered array and select one item from array by index.
function wiseQuote(){
// get value of input
var topic = document.getElementById("topic").value;
// filter array based of input value
var filteredQuotes = quotes.filter(function(val) {
return val.indexOf(topic) > -1;
});
// replace filtered array with origin array if it is empty
filteredQuotes = filteredQuotes.length > 0 ? filteredQuotes : quotes;
// generate random number
var rand = Math.floor(Math.random()*(filteredQuotes.length));
// insert target item into html
document.getElementById('quoteDisplay').innerHTML = filteredQuotes[rand];
}
function wiseQuote(){
var topic = document.getElementById("topic").value;
var filteredQuotes = quotes.filter(function(val) {
return val.indexOf(topic) > -1;
});
filteredQuotes = filteredQuotes.length > 0 ? filteredQuotes : quotes;
var rand = Math.floor(Math.random()*(filteredQuotes.length));
document.getElementById('quoteDisplay').innerHTML = filteredQuotes[rand];
}
var quotes = [
"You've gotta dance like there's nobody watching, Love like you'll never be hurt, Sing like there's nobody listening, And live like it's heaven on earth. - William W. Purkey",
"You know you're in love when you can't fall asleep because reality is finally better than your dreams. - Elbert Hubbard",
"Being deeply loved by someone gives you strength, while loving someone deeply gives you courage - Lao Tzu",
"In three words I can sum up everything I've learned about life: it goes on. - Robert Frost",
"Everything in moderation, including moderation - Oscar Wilde",
"Life isn't about finding yourself. Life is about creating yourself. - George Bernard Shaw",
"Life is like riding a bicycle. To keep your balance, you must keep moving. - Albert Einstein",
"The truth is rarely pure and never simple. - Oscar Wilde",
"A lie can travel half way around the world while the truth is putting on its shoes.- Mark Twain",
"Perhaps one did not want to be loved so much as to be understood. - George Orwell",
"Facts do not cease to exist because they are ignored. - Aldous Huxley",
"Above all, don't lie to yourself. The man who lies to himself and listens to his own lie comes to a point that he cannot distinguish the truth within him, or around him, and so loses all respect for himself and for others. And having no respect he ceases to love. - Fyodor Dostoevsky",
"A thing is not necessarily true because a man dies for it. - Oscar Wilde",
"The unexamined life is not worth living. - Socrates"
];
<p id="quoteDisplay"></p>
<form>
<input type="text" id="topic" />
<button type="button" onclick="wiseQuote()">Quote</button>
</form>
Below is a working solution; however I want to address a few things with your original code to help you out.
You come from a Java background, or copied a Java solution from somewhere. JavaScript doesn't have size(), it's length. Also, you can't use int to force a type, as Javascript is a loosely typed language.
You're <p> is inside the <body>, but your <form> is outside the <body>. You'll want to make sure and keep everything you want users to see inside the <body> element.
Array.prototype.filter() expects you to return true or false, nothing else will work.
Your wiseQuote function is literally closed before any of your code starts, tabbing your code will help you spot errors like this.
I removed the <form> element, since you're not actually submitting. This will allow you to not have to try to stop the page from refreshing with e.preventDefault().
function wiseQuote(){
var topic = document.getElementById("topic").value;
var randomIndex;
var filteredQuotes;
var filteredQuote;
if (topic != null){
filteredQuotes = quotes.filter(function(quote){
return quote.includes(topic);
});
}
if (filteredQuotes.length) {
randomIndex = Math.floor(Math.random() * filteredQuotes.length);
filteredQuote = filteredQuotes[randomIndex];
} else {
randomIndex = Math.floor(Math.random() * quotes.length);
filteredQuote = quotes[randomIndex];
}
document.getElementById('quoteDisplay').innerHTML = filteredQuote;
}
var quotes = [
"You've gotta dance like there's nobody watching, Love like you'll never be hurt, Sing like there's nobody listening, And live like it's heaven on earth. - William W. Purkey",
"You know you're in love when you can't fall asleep because reality is finally better than your dreams. - Elbert Hubbard",
"Being deeply loved by someone gives you strength, while loving someone deeply gives you courage - Lao Tzu",
"In three words I can sum up everything I've learned about life: it goes on. - Robert Frost",
"Everything in moderation, including moderation - Oscar Wilde",
"Life isn't about finding yourself. Life is about creating yourself. - George Bernard Shaw",
"Life is like riding a bicycle. To keep your balance, you must keep moving. - Albert Einstein",
"The truth is rarely pure and never simple. - Oscar Wilde",
"A lie can travel half way around the world while the truth is putting on its shoes.- Mark Twain",
"Perhaps one did not want to be loved so much as to be understood. - George Orwell",
"Facts do not cease to exist because they are ignored. - Aldous Huxley",
"Above all, don't lie to yourself. The man who lies to himself and listens to his own lie comes to a point that he cannot distinguish the truth within him, or around him, and so loses all respect for himself and for others. And having no respect he ceases to love. - Fyodor Dostoevsky",
"A thing is not necessarily true because a man dies for it. - Oscar Wilde",
"The unexamined life is not worth living. - Socrates"
];
<input type="text" id="topic" />
<button onclick="wiseQuote()">Quote</button>
<p id="quoteDisplay"></p>

Write the text with typing effect using javascript/Jquery

I will receive some content from server side.What I trying is to make the typing effect at the time of display this content.
$("#dislay").click(function() {
//this is the dummy content i will recieve from server
var contentFromServer = "Smile spoke total few great had never their too. Amongst moments do in arrived at my replied. Fat weddings servants but man believed prospect. Companions understood is as especially pianoforte connection introduced. Nay newspaper can sportsman are admitting gentleman belonging his. Is oppose no he summer lovers twenty in. Not his difficulty boisterous surrounded bed. Seems folly if in given scale. Sex contented dependent conveying advantage can use. Do play they miss give so up. Words to up style of since world. We leaf to snug on no need. Way own uncommonly travelling now acceptance bed compliment solicitude. Dissimilar admiration so terminated no in contrasted it. Advantages entreaties mr he apartments do. Limits far yet turned highly repair parish talked six. Draw fond rank form nor the day eat. In post mean shot ye. There out her child sir his lived. Design at uneasy me season of branch on praise esteem. Abilities discourse believing consisted remaining to no. Mistaken no me denoting dashwood as screened. Whence or esteem easily he on. Dissuade husbands at of no if disposal.";
var typerText = "";
var contentLength = contentFromServer.length;
var count = 0;
var typingSpeed = 100000 / contentLength;
var typer = setInterval(function() {
if (count > contentFromServer.length) { clearInterval(typer); }
typerText += contentFromServer.charAt(count);
document.getElementById("dislayArea").innerHTML = "" + typerText + "";
count++;
}, typingSpeed);
//reset the interval on click of button
$("#dislay").click(function() { clearInterval(typer); });
});
div {
border: 1px solid gray;
padding: 8px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="dislay" type="button">Display Content</button>
<div id="dislayArea"></div>
The question is I do not know if I'm using the correct way or not. That is, not sure if it would be better to use the for loop, or use setInterval(what I am using). Or there is any better approach to do this.
Using setInterval() is definitely better than loop statement, as using loop will block your JS execution and you would not be able to do something during the same time. To avoid this you may use variable speed based on string length (as you have done) but IMO this will not give good visual experience.
I will also suggest to take a look at typed.js library. (There can be other libraries that achieve the same task, but I have experience with this library and it works great!)
Using the library provides more flexible control over the task with various options and again why to reinvent the wheel ?
Here is an example snippet of typed.js:
var typed = null;
$("#dislay").click(function() {
if(typed != null)
typed.destroy();
var contentFromServer = "Smile spoke total few great had never their too. Amongst moments do in arrived at my replied. Fat weddings servants but man believed prospect. Companions understood is as especially pianoforte connection introduced. Nay newspaper can sportsman are admitting gentleman belonging his. Is oppose no he summer lovers twenty in. Not his difficulty boisterous surrounded bed. Seems folly if in given scale. Sex contented dependent conveying advantage can use. Do play they miss give so up. Words to up style of since world. We leaf to snug on no need. Way own uncommonly travelling now acceptance bed compliment solicitude. Dissimilar admiration so terminated no in contrasted it. Advantages entreaties mr he apartments do. Limits far yet turned highly repair parish talked six. Draw fond rank form nor the day eat. In post mean shot ye. There out her child sir his lived. Design at uneasy me season of branch on praise esteem. Abilities discourse believing consisted remaining to no. Mistaken no me denoting dashwood as screened. Whence or esteem easily he on. Dissuade husbands at of no if disposal.";
var typedOptions = {
strings: [contentFromServer],
typeSpeed: 60,
showCursor: false
};
typed = new Typed("#displayArea", typedOptions);
});
div {
border: 1px solid gray;
padding: 8px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/typed.js/2.0.8/typed.js"></script>
<button id="dislay" type="button">Display Content</button>
<div id="displayArea"></div>

Can you use an if/else inside a .filter() / Is there any other way?

TASK:
There is an array of words called overusedWords. These are words overused in this story. You want to let the user of your program know how many times they have used these overused words. There are two ways to achieve this. Try it on your own first. If you need help, consult the hint.
HINT:
1.You can iterate over the betterWords array three separate times (once for each of the words in the overusedWords array). Create a variable that represents the total times that word appears. Add 1 to the variable every time the current word is the same as that word.
2.You can make this simpler by using one if, and two else if statements in the function code block of your iterator. That way, you can gather the counts of all three overused words at one time.
CODE:
let story = 'Last weekend, I took literally the most beautiful bike ride of
my life. The route is called "The 9W to Nyack" and it actually stretches
all the way from Riverside Park in Manhattan to South Nyack, New Jersey.
It\'s really an adventure from beginning to end! It is a 48 mile loop and
it basically took me an entire day. I stopped at Riverbank State Park to
take some extremely artsy photos. It was a short stop, though, because I
had a really long way left to go. After a quick photo op at the very
popular Little Red Lighthouse, I began my trek across the George
Washington Bridge into New Jersey. The GW is actually very long - 4,760
feet! I was already very tired by the time I got to the other side. An
hour later, I reached Greenbrook Nature Sanctuary, an extremely beautiful
park along the coast of the Hudson. Something that was very surprising
to me was that near the end of the route you actually cross back into New
York! At this point, you are very close to the end.';
let storyWords = story.split(' ')
console.log(storyWords)
console.log(storyWords.length)
let overusedWords = ['really', 'very', 'basically'];
let unnecessaryWords = ['extremely', 'literally', 'actually' ];
let betterWords = storyWords.filter( storyWords =>
!unnecessaryWords.includes(storyWords.toLowerCase()));
console.log(betterWords)
You can define your own function to act as the filter. For example if I was given an array of ages and only wanted to return the ages over between 20 and 35 I could do the following:
var ages = [32, 33, 16, 40];
console.log(ages.filter(checkAge));
function checkAge(age) {
if (age > 20 && age < 35) {
return age;
}
}
this returns an output of:
Array [ 32, 33 ]
What about using Array.prototype.reduce() and a single if?
const story = `Last weekend, I took literally the most beautiful bike ride of
my life. The route is called "The 9W to Nyack" and it actually stretches
all the way from Riverside Park in Manhattan to South Nyack, New Jersey.
It\'s really an adventure from beginning to end! It is a 48 mile loop and
it basically took me an entire day. I stopped at Riverbank State Park to
take some extremely artsy photos. It was a short stop, though, because I
had a really long way left to go. After a quick photo op at the very
popular Little Red Lighthouse, I began my trek across the George
Washington Bridge into New Jersey. The GW is actually very long - 4,760
feet! I was already very tired by the time I got to the other side. An
hour later, I reached Greenbrook Nature Sanctuary, an extremely beautiful
park along the coast of the Hudson. Something that was very surprising
to me was that near the end of the route you actually cross back into New
York! At this point, you are very close to the end.`;
const storyWords = story.toLowerCase().split(' ');
const overusedWords = ['really', 'very', 'basically'];
const results = storyWords.reduce((acc, word) => {
if (overusedWords.includes(word)) {
acc[word] = (acc[word] || 0) + 1;
}
return acc;
}, {});
console.log(results)
As you can see in this example, can also call String.prototype.toLowerCase() a single time outside filter()/reduce().
If you still prefer to use filter(), the example above should be easy to adapt, so I'll leave that for you.

Microsoft Translate Voice limit 200-400 words when request

I have a URL of Microsoft Translate Voice to get voice look like:
<audio controls autoplay>
<source src="https://www.bing.com/tspeak?&format=audio%2Fmp3&language=en&IG=D2CBB80AA6824D9A91B0A5D1074FC4A1&IID=translator.5034.2&text=I’m Often at the End of My Rope as a Mom of Two" type="audio/mpeg">
</audio>
The problem is: text="any text here". Any text here is limit about 200-400 word. I don't know the reason at here. In Bing Translate I can insert full 5000 words and click button audio to hear.
Have any method to pass this problem? Microsoft is limit in this URL?
Have any method to insert 5000 words like Microsoft Translate homepage?
If you open your developer console on Bing's website and start playing the sound, you'll see it sends a first mp3 request with only a couple of words, and when it's done reading it, it sends another one, and so on.
You could do the same:
// When the DOM (basically the HTML) is loaded
document.addEventListener('DOMContentLoaded', function(){
// Define your DOM elements
var getAudioBtn = document.getElementById('getAudioBtn'),
langSelect = document.getElementById("langSelect"),
langSource = document.getElementById("langSource"),
audioEl = document.getElementById('audioEl');
// Setup an event listener on the button
getAudioBtn.addEventListener('click', getContentTranslate);
// Setup an listener on the audio onended event
audioEl.addEventListener('ended', readChunkQueue);
var chunkQueue = [], // Queue of chunks of text to read
wordsPerChunk = 80, // Words per chunk
language = 'en'; // Default language
function getContentTranslate() {
// Store the language
language = langSelect.value;
// Empty the chunks array
chunkQueue = [];
// Split the text into words
var words = langSource.value.split(/ /g),
tmp = []; // Temporary array for creating a chunk
while(words.length) {
// If out temporary chunk is full, add it to the list
if (tmp.length === wordsPerChunk) {
chunkQueue.push(tmp.join(' '));
tmp = [];
}
tmp.push(words.shift());
}
if (tmp.length) {
chunkQueue.push(tmp.join(' '));
}
// Start reading these chunks
readChunkQueue();
}
function readChunkQueue() {
// If the list is empty, stop
if (!chunkQueue.length) {
return;
}
// Get the first chunk in the list
var chunk = chunkQueue.shift(),
url = 'https://www.bing.com/tspeak?&format=audio%2Fmp3'
+ '&language=' + encodeURIComponent(language)
+ '&IG=D2CBB80AA6824D9A91B0A5D1074FC4A1&IID=translator.5034.2'
+ '&text=' + encodeURIComponent(chunk);
// Set the URL as source for the audio element
audioEl.setAttribute('src', url);
}
});
<select id="langSelect">
<option value="en">English</option>
<option value="vi">Vietnamese</option>
</select>
<br>
<textarea id="langSource" placeholder="Enter text or webpage URL here">Obama Inaugural Address. 20th January 2009. My fellow citizens: I stand here today humbled by the task before us, grateful for the trust you have bestowed, mindful of the sacrifices borne by our ancestors. I thank President Bush for his service to our nation, as well as the generosity and cooperation he has shown throughout this transition. Forty-four Americans have now taken the presidential oath. The words have been spoken during rising tides of prosperity and the still waters of peace. Yet, every so often the oath is taken amidst gathering clouds and raging storms. At these moments, America has carried on not simply because of the skill or vision of those in high office, but because We the People have remained faithful to the ideals of our forbearers, and true to our founding documents. So it has been. So it must be with this generation of Americans. That we are in the midst of crisis is now well understood. Our nation is at war, against a far-reaching network of violence and hatred. Our economy is badly weakened, a consequence of greed and irresponsibility on the part of some, but also our collective failure to make hard choices and prepare the nation for a new age. Homes have been lost; jobs shed; businesses shuttered. Our health care is too costly; our schools fail too many; and each day brings further evidence that the ways we use energy strengthen our adversaries and threaten our planet. These are the indicators of crisis, subject to data and statistics. Less measurable but no less profound is a sapping of confidence across our land - a nagging fear that America's decline is inevitable, and that the next generation must lower its sights. Today I say to you that the challenges we face are real. They are serious and they are many. They will not be met easily or in a short span of time. But know this, America - they will be met. On this day, we gather because we have chosen hope over fear, unity of purpose over conflict and discord. On this day, we come to proclaim an end to the petty grievances and false promises, the recriminations and worn out dogmas, that for far too long have strangled our politics. We remain a young nation, but in the words of Scripture, the time has come to set aside childish things. The time has come to reaffirm our enduring spirit; to choose our better history; to carry forward that precious gift, that noble idea, passed on from generation to generation: the God-given promise that all are equal, all are free, and all deserve a chance to pursue their full measure of happiness. In reaffirming the greatness of our nation, we understand that greatness is never a given. It must be earned. Our journey has never been one of short-cuts or settling for less. It has not been the path for the faint-hearted - for those who prefer leisure over work, or seek only the pleasures of riches and fame. Rather, it has been the risk-takers, the doers, the makers of things - some celebrated but more often men and women obscure in their labor, who have carried us up the long, rugged path towards prosperity and freedom.</textarea>
<br>
<button id="getAudioBtn">GET AUDIO</button>
<br>
<audio id="audioEl" autoplay controls></audio>

Quotes script not working

I have a script to display random quotes after clicking on button. Please help me understand why it is not working.
function quotes() {
var aquote = new Array;
aquote[0] = "\"Nobody exists on purpose. Nobody belongs anywhere. We're all
going to die.Come watch TV.\"";
aquote[1] = "\"Listen, Morty, I hate to break it to you but what people call
love is just a chemical reaction that compels animals to breed.It hits
hard, Morty, then it slowly fades, leaving you stranded in a failing
marriage.I did it.Your parents are gonna do it.Break the cycle, Morty.
Rise above.Focus on science."\"";
aquote[2] = "\"Weddings are basically funerals with cake.\""
aquote[3] = "\"There is no God, Summer. Gotta rip that band-aid off now
you’ ll thank me later.\""
aquote[4] = "\"I’m sorry, but your opinion means very little to me.\""
aquote[5] = "\"Being nice is something stupid people do to hedge their
bets.\""
rdmQuote = Math.floor(Math.random() * aquote.length);
document.getElementById("quote").value = aquote[rdmQuote];
}
window.onload = quotes;
<marquee><p id="quote"></p></marquee>
You have a syntax error on the aquote[1] line. In the end it should be Focus on science.\""; instead of Focus on science."\"";. Note the third quote from the end.
Once that is fixed, you need to set the innerText of quote, rather than its value. See the working snippet below:
<script>
function quotes(){
var aquote = new Array;
aquote[0]="\"Nobody exists on purpose. Nobody belongs anywhere. We're all going to die. Come watch TV.\"";
aquote[1]="\"Listen, Morty, I hate to break it to you but what people call love is just a chemical reaction that compels animals to breed. It hits hard, Morty, then it slowly fades, leaving you stranded in a failing marriage. I did it. Your parents are gonna do it. Break the cycle, Morty. Rise above. Focus on science.\"";
aquote[2]="\"Weddings are basically funerals with cake.\""
aquote[3]="\"There is no God, Summer. Gotta rip that band-aid off now you’ll thank me later.\""
aquote[4]="\"I’m sorry, but your opinion means very little to me.\""
aquote[5]="\"Being nice is something stupid people do to hedge their bets.\"";
rdmQuote = Math.floor(Math.random()*aquote.length);
document.getElementById("quote").innerText=aquote[rdmQuote];
}
window.onload=quotes;
</script>
<marquee><p id="quote"></p></marquee>
I see a couple problems. First line breaks are messing up where you declare the values. Second, you have an extra " mark on one of the lines. And last, you need to change the innerHTML not the value. Try this instead:
function quotes() {
var aquote = new Array;
aquote[0]="\"Nobody exists on purpose. Nobody belongs anywhere. We're all going to die. Come watch TV.\"";
aquote[1]="\"Listen, Morty, I hate to break it to you but what people call love is just a chemical reaction that compels animals to breed. It hits hard, Morty, then it slowly fades, leaving you stranded in a failing marriage. I did it. Your parents are gonna do it. Break the cycle, Morty. Rise above. Focus on science.\"";
aquote[2]="\"Weddings are basically funerals with cake.\"";
aquote[3]="\"There is no God, Summer. Gotta rip that band-aid off now you’ll thank me later.\"";
aquote[4]="\"I’m sorry, but your opinion means very little to me.\"";
aquote[5]="\"Being nice is something stupid people do to hedge their bets.\"";
rdmQuote = Math.floor(Math.random()*aquote.length);
document.getElementById("quote").innerHTML=aquote[rdmQuote];
}
window.onload=quotes;

Categories