javascript random quote generator not printing - javascript

I'm trying to generate a fresh quote from a list on every refresh. For some reason, I can't get the quotes to show up within the div, and I'm not sure why.
Any help would be greatly appreciated!
<div id="quotes">
<script>
var quotes = new Array();
quotes[0] = "<i>Quote 1</i><br><b>Author</b>";
quotes[1] = "<i>Quote 2</i><br><b>Author</b>";
var random = Math.ceil (Math.random() * quotes.length) - 1;
$('quotes').set('html', quotes[random]);
</script>
</div>
I've updated my code thanks to everyones help to this-
<div id="quotes"></div>
<script>
var quotes = [
"<i>"Some people feel the rain. Others just get wet."</i><br><b>Bob Marley/b>",
"<i>“Do not pray for an easy life, pray for the strength to endure a difficult one.”</i><br><b>Bruce Lee</b>",
"<i>“Success is not final, failure is not fatal: it is the courage to continue that counts.”</i><br><b>Winston
Churchill</b>",
"<i>If your dreams don’t scare you they’re not big enough.</i><br><b></b>",
"<i>“It takes courage to grow up and become who you really are.”</i><br><b>E.E. Cummings</b>",
"<i>All endings are also beginnings, we just don’t know it yet.</i><br><b></b>",
"<i>There are three kinds of people: Those who make it happen, those who watch it happen, and
those who wonder what the heck happened.</i><br><b></b>",
"<i>There are people so poor, that the only thing they have is money.</i><br><b></b>",
"<i>“Things do not happen. Things are made to happen.”</i><br><b>John F. Kennedy</b>",
"<i>“Destiny is a name often given in retrospect to choices that had dramatic consequences.”</i><br><b>J.K. Rowling</b>",
"<i>“When I was 5 years old, my mother always told me that happiness was the key to life.
When I went to school, they asked me what I wanted to be when I grew up. I wrote
down ‘happy’. They told me I didn’t understand the assignment, and I told them they didn’t
understand life.”</i><br><b>John Lennon</b>",
"<i>“Not all those who wander are lost”</i><br><b>JRR Tolkien</b>",
"<i>We all die. The goal isn’t to live forever, the goal is to create something that will.</i><br><b></b>",
"<i>Strive for progress, not perfection.</i><br><b></b>",
"<i>What defines us is how well we rise after falling.</i><br><b></b>",
"<i>“It’s not hard to make decisions once you know what your values are.”</i><br><b>Roy E. Disney</b>",
"<i>Sorry’s not good enough.</i><br><b></b>",
"<i>I may not be there yet, but I’m closer than I was yesterday.
Every day is a new beginning. Stay away from what might have been and look at what can
be.</i><br><b></b>",
"<i>Who inspires you?</i><br><b></b>",
"<i>“If you play by the rules long enough, then you can change the game.”</i><br><b>Enders Game</b>"
];
document.getElementById('quotes').innerHTML = quotes[Math.floor(Math.random() * quotes.length)];
</script>
For some reason, the div is still loading without any content thought.
It was the quotes inside of my quotes messing it up. Thank you everyone for the help!!

Removing the need for any library makes the code a lot easier to not botch.
<div id="quotes"></div>
<script>
var quotes = [
"<i>Quote 1</i><br><b>Author</b>",
"<i>Quote 2</i><br><b>Author</b>"
];
document.getElementById('quotes').innerHTML =
quotes[Math.floor(Math.random() * quotes.length)];
</script>

EDIT: Nevermind, seems like $ in MooTools should indeed return the element with the id quotes. If you wanted to do the same thing with no frameworks, you could use document.getElementById('quotes').innerHTML = quotes[random].
Your $ is trying to find an element called <quotes>, not an element with the id "quotes" (assuming that it uses CSS selectors like jQuery). Using $('#quotes') should fix it.
A few other things: You could write the array in a much more concise fashion:
quotes = [
"<i>Quote 1</i><br><b>Author</b>",
"<i>Quote 2</i><br><b>Author</b>"
];
Also, you could just use Math.floor instead of Math.ceil for your random value, then you wouldn't need the - 1 at the end.

Related

I am unable to understand how to code a logic for money splitting among group of people using MEAN

I am working on a project named "Splitter", where I need to create a group and split the money among N number of people in short similar to splitwise app but I am confused at the logic part, where every individual can update the amount and get the overall amount an individual gets or owes others.
Please let me know if you need more clarification on my question. Any leads would be appreciated.
A pseudo-code would be:
amount_every_person_owes = total_spent / number_of_people
for person in group:
amount_this_person_owes = amount_every_person_owes - amount_this_person_spent
Of course, after arriving at the amount each person owes, you'll have to create a mapping as to who owes how much to the other. I'll leave that part to you.

Numbers from inside a string without regex?

I'm making a bot for a gaming chatroom with some friends, but I've hit an impasse. Is there a reliable way to get numbers from inside a string of text that won't completely break an inexperienced script kiddy's brain? Here's the best I've been able to come up with so far, variables simplified slightly for illustration's sake:
var k = [0];
function dieRoll(m,n) {
for(i = 0; i < m; i++) {
k[i] = Math.floor(Math.random()*n)+1;
}
}
var m = text[5];
var n = text[7];
if (text === 'roll '+m+'d'+n) {
dieRoll(m,n)
console.log(k);
}
The biggest problem as-is is that it's limited to single-digit input.
EDIT: Looping through the text looking for integers is exactly the kind of thing I'm looking for. I don't have much experience with programming, so I probably tend to end up with overly complicated and confusing messes of spaghetti code that would embarrass anyone remotely professional. As for the format of the input I'm looking for, "roll [number of dice]d[highest number on the dice]". For anyone who doesn't know, it's the notation most tabletop rpgs use. For example, "roll 2d6" for two normal six-sided dice.
EDIT: It's not that I'm necessarily against regex, I just want to be able to understand what's going on, so that if and when I need to edit or reuse the code it I can do so without going completely insane.
EDIT: Thank you all very much! split() seems to be exactly what I was looking for! It'll probably take some trial and error, but I think I'll be able to get her working how she's supposed to this weekend (Yes I call my bots 'she').
Basically, you need to look at the format of the input you're using, and identify certain facts about it. Here are the assumptions I've taken based on your question.
1) The "roll" command comes first followed by a space, and
2) After the command, you are provided with dice information in the form xdy.
Here's something that should work given those constraints:
function getRollParameters(inputCommand) {
var inputWords = inputCommand.split(' '); //Split our input around the space, into an array containing the text before and after the space as two separate elements.
var diceInfo = inputWords[1]; //Store the second element as "diceInfo"
var diceDetails = diceInfo.split('d'); //Split this diceInfo into two sections, that before and after the "d" - ie, the number of dice, and the sides.
//assign each part of the dicedetails to an appropriate variable
var dice = diceDetails[0];
var sides = diceDetails[1];
//return our two pieces of information as a convenient object.
return {
"dice": dice,
"sides": sides
};
}
//a couple of demonstrations
console.log(getRollParameters("roll 5d8"));
console.log(getRollParameters("roll 126d2"));
Effectively, we're first splitting the string into the "command", and the "arguments" - the information we want. Then, we split our arguments up using the "d" as a midpoint. That gives us two numbers - the one before and the one after the d. Then we assign those values to variables, and can use them however we like.
This obviously won't deal with more creative or flexible inputs, and isn't tested beyond the examples shown but it should be a decent starting point.

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;

Javascript random quote generator NO REPEAT

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.

javascript array only works when not completely full of content

I have an array full of quotes, and on load a random quote is displayed. The problem I'm having is everything works fine when I only have 2 quotes loaded, but when I added the entire list, it no longer runs.
Here is the code that works-
<div id="quotes">Quotes</div>
<script type="text/javascript">
var quotes = [
"<i>Some people feel the rain. Others just get wet.</i><br><b>Bob Marley</b>",
"<i>Do not pray for an easy life, pray for the strength to endure a difficult one. </i><br><b>Bruce Lee</b>"
];
document.getElementById('quotes').innerHTML = quotes[Math.floor(Math.random() * quotes.length)];
</script>
The above works as expected, however when I add the rest of the quotes (as seen below) The script no longers works.
<div id="quotes"></div>
<script type="text/javascript">
var quotes = [
"<i>Some people feel the rain. Others just get wet.</i><br><b>Bob Marley/b>",
"<i>Do not pray for an easy life, pray for the strength to endure a difficult one. </i><br><b>Bruce Lee</b>",
"<i>Success is not final, failure is not fatal: it is the courage to continue that counts.</i><br><b>Winston
Churchill</b>",
"<i>If your dreams don’t scare you they’re not big enough.</i><br><b></b>",
"<i>It takes courage to grow up and become who you really are.</i><br><b>E.E. Cummings</b>",
"<i>All endings are also beginnings, we just don’t know it yet.</i><br><b></b>",
"<i>There are three kinds of people: Those who make it happen, those who watch it happen, and
those who wonder what the heck happened.</i><br><b></b>",
"<i>There are people so poor, that the only thing they have is money.</i><br><b> </b>",
"<i>Things do not happen. Things are made to happen.</i><br><b>John F. Kennedy</b>",
"<i>Destiny is a name often given in retrospect to choices that had dramatic consequences.</i><br><b>J.K. Rowling</b>",
"<i>When I was 5 years old, my mother always told me that happiness was the key to life.
When I went to school, they asked me what I wanted to be when I grew up. I wrote
down ‘happy’. They told me I didn’t understand the assignment, and I told them they didn’t
understand life.</i><br><b>John Lennon</b>",
"<i>Not all those who wander are lost</i><br><b>JRR Tolkien</b>",
"<i>We all die. The goal isn’t to live forever, the goal is to create something that will.</i><br><b></b>",
"<i>Strive for progress, not perfection.</i><br><b></b>",
"<i>What defines us is how well we rise after falling.</i><br><b></b>",
"<i>It’s not hard to make decisions once you know what your values are.</i><br><b>Roy E. Disney</b>",
"<i>Sorry’s not good enough.</i><br><b></b>",
"<i>I may not be there yet, but I’m closer than I was yesterday.
Every day is a new beginning. Stay away from what might have been and look at what can
be.</i><br><b></b>",
"<i>Who inspires you?</i><br><b></b>",
"<i>If you play by the rules long enough, then you can change the game.</i><br> <b>Enders Game</b>"
];
document.getElementById('quotes').innerHTML = quotes[Math.floor(Math.random() * quotes.length)];
</script>
You can't have newlines in JavaScript strings. You need to change this:
"str part
the rest"
to this:
"str part\nthe rest"
or
"str part\n"
+ "the rest"
You should check the JavaScript console for errors; this can help you debug
Also, you can write multiple-lined strings like this:
var str = "beginning \
continue \
end.";
The backslash before the line break is another solution.
The line breaks inside strings caused the issue. Here is fully working code:http://jsfiddle.net/whizkid747/5tyrY/
<div id="quotes">Quotes</div>
<script type="text/javascript">
var quotes = [
"<i>Some people feel the rain. Others just get wet.</i><br><b>Bob Marley</b>",
"<i>Do not pray for an easy life, pray for the strength to endure a difficult one.</i><br><b>Bruce Lee</b>",
"<i>Success is not final, failure is not fatal: it is the courage to continue that counts.</i><br><b>WinstonChurchill</b>",
"<i>If your dreams don’t scare you they’re not big enough.</i><br><b></b>",
"<i>It takes courage to grow up and become who you really are.</i><br><b>E.E. Cummings</b>",
"<i>All endings are also beginnings, we just don’t know it yet.</i><br><b></b>",
"<i>There are three kinds of people: Those who make it happen, those who watch it happen, and those who wonder what the heck happened.</i><br><b></b>",
"<i>There are people so poor, that the only thing they have is money.</i><br><b> </b>",
"<i>Things do not happen. Things are made to happen.</i><br><b>John F. Kennedy</b>",
"<i>Destiny is a name often given in retrospect to choices that had dramatic consequences.</i><br><b>J.K. Rowling</b>",
"<i>When I was 5 years old, my mother always told me that happiness was the key to life. When I went to school, they asked me what I wanted to be when I grew up. I wrote down ‘happy’. They told me I didn’t understand the assignment, and I told them they didn’t understand life.</i><br><b>John Lennon</b>",
"<i>Not all those who wander are lost</i><br><b>JRR Tolkien</b>",
"<i>We all die. The goal isn’t to live forever, the goal is to create something that will.</i><br><b></b>",
"<i>Strive for progress, not perfection.</i><br><b></b>",
"<i>What defines us is how well we rise after falling.</i><br><b></b>",
"<i>It’s not hard to make decisions once you know what your values are.</i><br><b>Roy E. Disney</b>",
"<i>Sorry’s not good enough.</i><br><b></b>",
"<i>I may not be there yet, but I’m closer than I was yesterday. Every day is a new beginning. Stay away from what might have been and look at what can be.</i><br><b></b>",
"<i>Who inspires you?</i><br><b></b>",
"<i>If you play by the rules long enough, then you can change the game.</i><br> <b>Enders Game</b>"
];
document.getElementById('quotes').innerHTML = quotes[Math.floor(Math.random() * quotes.length)];
</script>

Categories