random quote without back to back - javascript

I'm trying to pull a random quote from an array. I need to display an initial quote and then get a new one, no same two quotes back to back. Here's what I got.
$(document).ready(function() {
var quoter = [{
quote: "I drink to make other people more interesting.",
author: "Ernest Hemingway"
}, {
quote: "Alcohol may be man's worst enemy, but the bible says love your enemy.",
author: "Frank Sinatra"
}, {
quote: "Reality is an illusion created by a lack of alcohol.",
author: "N.F. Simpson"
},{
quote: "Time is never wasted when you’re wasted all the time.",
author: "Catherine Zandonella"
},{
quote: "I feel bad for people who don’t drink. When they wake up in the morning, that’s as good as they’re going to feel all day.",
author: "Frank Sinatra"
}];
var randomQuote = Math.floor(Math.random() * quoter.length);
//$(function () {
//Set Original Quote
$('#quoteText').text(quoter[randomQuote].quote);
$('#authorText').text(quoter[randomQuote].author);
//});
$('#btnNew').click(function(evt) {
//prevent browser's default action
evt.preventDefault();
//getting a new random number to attach to a quote and setting a limit
var sourceLength = quoter.length;
var randomNumber = Math.floor(Math.random() * sourceLength);
//set a new quote
//while ( randomNumber <= sourceLength ) {
while (randomNumber === randomNumber){
var newQuoteText = quoter[randomNumber].quote;
var newQuoteGenius = quoter[randomNumber].author;
var timeAnimation = 500;
var quoteContainer = $('#quoteContainer');
//fade out animation with callback
quoteContainer.fadeOut(timeAnimation, function() {
//set text values
$('#quoteText').text(newQuoteText);
$('#authorText').text(newQuoteGenius);
//console.log(quoteText,authorText);
//fadein animation.
quoteContainer.fadeIn(timeAnimation);
});
break;
}; //end while loop
}); //end btnNew function
}); //end document ready
I need to do this by using a while loop. I can't figure out how to store the random quote (array value) and then compare it to the new random one to get a different random on if it's the same.
The HTML is here:
<div id="quoteContainer">
<p><span id="quoteText"></span><Br/></p>
—<span id="authorText"> </span>
</div>

You can have a simple variable store the previous value, then check to see if the random number is the same as the last time.
$(document).ready(function(){
//....your current above code
var lastQuote = randomQuote;
$(button).click(function(){
var thisQuote = Math.floor(Math.random() * sourceLength);
//This will only be entered if the two are equal
//The while loop ensures that if you get a new random number
//it won't be the same
while(thisQuote == lastQuote){
thisQuote = Math.floor(Math.random() * sourceLength);
}
//If you make it here a unique number has been found
lastQuote = thisQuote;
});
});

Your approach might result in an infinite loop. Won't happen, because the random-number generator is not perfect but it can be done easier:
Either shuffel the array and go down linearly (or construct a fancy generator if you want) or just delete every quote that has been shown already.

Related

How do I make a random quote generator not repeat quotes

I've searched the site for answers but the one's that come up aren't similar/specific to the code that I have written. I don't know how to modify the code so that the quotes don't repeat when the user presses a button to generate another quote.
var quotes = [
{
quote: "\"Don't just exist, live\""
},
{
quote: "\"Try to be a rainbow in someone's cloud\""
},
{
quote: "\"Prove them wrong\""
},
{
quote: "\"Find reasons to smile\""
},
{
quote: "\"You get what you give\""
}
]
var quotebtn = document.getElementById('quote-btn');
var quote = document.querySelector('.quote');
quotebtn.addEventListener('click', () => {
let random = Math.floor(Math.random() * quotes.length);
quote.innerHTML = quotes[random].quote;
})
If the displayed is no longer important and can be deleted. You can do it easily with an array splice.
example:
var quotes = [
{
quote: "\"Don't just exist, live\""
},
{
quote: "\"Try to be a rainbow in someone's cloud\""
},
{
quote: "\"Prove them wrong\""
},
{
quote: "\"Find reasons to smile\""
},
{
quote: "\"You get what you give\""
}
]
var quotebtn = document.getElementById('quote-btn');
var quote = document.querySelector('.quote');
quotebtn.addEventListener('click', () => {
let random = Math.floor(Math.random() * quotes.length);
quote.innerHTML = quotes[random].quote;
quotes.splice(random, 1); // Trim one from the specified index.
})
This should work for you
quotebtn.addEventListener('click', () => {
if(quotes.length) {
let random = Math.floor(Math.random() * quotes.length);
quote.innerHTML = quotes[random].quote;
quotes.splice(random, 1);
} else {
quote.innerHTML = "No more quotes!";
}
})
quotes.splice(random, 1) removes quotes already presented from the array, preventing it from repeating
Once quotes is emptied, the No more quotes! message can be displayed!
You can make another array with the same length as the quotes array and initialize it with zeros. When quote is generated set the new array at the same index as the quote to one which will mean that the quote is already generated. Next time when you generate quote check first if quote is already generated and if it is generate again.
var quotes = [{
quote: "\"Don't just exist, live\""
},{
quote: "\"Try to be a rainbow in someone's cloud\""
},{
quote: "\"Prove them wrong\""
},{
quote: "\"Find reasons to smile\""
},{
quote: "\"You get what you give\""
}];
quotes.sort(() => Math.random() - 0.5);
var quotebtn = document.getElementById('quote-btn');
var quote = document.querySelector('.quote');
var actualQuote = 0;
quotebtn.addEventListener('click', () => {
if(actualQuote>=quotes.length){
quote.innerHTML = "No more quotes";
} else {
quote.innerHTML = quotes[actualQuote % quotes.length].quote;
actualQuote++;
}
});
<button id="quote-btn">Quote</button><br>
<span class="quote"></span>
I just shuffle the quotes at start. At click I display the first, and the next one, etc.
If you want it not to stop after last one just remove the condition and it will cycle trough all. So after the last it will start from the beginning.

Need help on using random to get a random string from array

I already know how to pull random from an array but this won't work. Trying to make an HTML game.
I use Caret.
I'm pretty new to coding but know most of the basics.
function person() {
...
interests = ["food", "clothes", "tech"]; //interest definition because I keep getting "undefined"
var rand = Math.floor(Math.random() * 3); //random var
instrestscho = interests[rand]; //interest random string puller that's not working
...
}
}
I spy an extra:
}
I'm guessing this is the error because everything else should work.
Also, if the point of this function is to grab a random interest, you may want to return it, like so:
function person() {
interests = ["food", "clothes", "tech"]; //interests definition
var rand = Math.floor(Math.random() * interests.length); //random var
return interests[rand]; //return interest random string
}
console.log( person() );

Using jQuery and Math.random() to select nested objects properties

I'm creating a random quote machine that will present a random quote from various philosophers.
I have an object literal with nested objects containing philosophers and their quotes. Using jQuery functions and Math.random(), how can I select a random quote from my object literal structure? Is there a better way to organize the data?
I've started with a jQuery closure that will display a designated quote that I'd like to modify using Math.random().
Looking for explanations to solutions as I'm a beginner. Thanks in advance.
Example object literal:
var quotes =
{
awatts: {
name: "Alan Watts",
quote: "The only way to make sense out of change is to plunge into it, move with it, and join the dance."
},
etolle: {
name: "Eckhart Tolle",
quote: "Realize deeply that the present moment is all you ever have."
},
tmckenna: {
name: "Terrence Mckenna",
quote: "“The cost of sanity in this society, is a certain level of alienation” "
}
};
Example jQuery functions with single quote selected:
$(document).ready(function() {
$('.mybutton').click(function() {
$('#quote').html(quotes.awatts.quote);
});
});
The structure of the data seems fine. You could use an array, but an object isn't a problem.
You'd get the keys from the object, and then pick a random key
var quotes = {
awatts: {
name: "Alan Watts",
quote: "The only way to make sense out of change is to plunge into it, move with it, and join the dance."
},
etolle: {
name: "Eckhart Tolle",
quote: "Realize deeply that the present moment is all you ever have."
},
tmckenna: {
name: "Terrence Mckenna",
quote: "“The cost of sanity in this society, is a certain level of alienation” "
}
};
$('.mybutton').click(function() {
var keys = Object.keys(quotes);
var rand = keys[Math.floor(Math.random() * keys.length)];
$('#quote').html(quotes[rand].quote);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="mybutton">Quote</button>
<br><br>
<div id="quote"></div>
If you can make your quotes object an array, the following would do the trick. Change your array
var quotes = [
{
name: "Alan Watts",
quote: "The only way to make sense out of change is to plunge into it, move with it, and join the dance."
},
{
name: "Eckhart Tolle",
quote: "Realize deeply that the present moment is all you ever have."
},
{
name: "Terrence Mckenna",
quote: "“The cost of sanity in this society, is a certain level of alienation” "
}
];
Set the max and min (to set the upper and lower limits for the random number)
var max = quotes.length, min = 0;
Generate a random number
var rand = Math.random() * (max - min) + min;
On the click event use the random number to choose your random quote
$('#quote').html(quotes[rand]quote);
I have not tested the code. Hope this will get you going :-)

JavaScript Random Function does not work

All I want to do is have the program select random questions (each question is within a function and fills a blank area in the HTML so all questions appear in the same area) but it does not work. Does anyone have any idea why? I am meant to click correct answer and it executes the correctFunction but nothing happens. Cheers!
var randomFunctions = [
"Question2", "Question3",
"Question4", "Question5",
"Question6", "Question7",
"Question8"
];
var rand = randomFunctions[Math.floor(Math.random() * randomFunctions.length)];
function correctFunction() {
rand();
}
correctFunction()
You must provide actual functions that can be invoked, not strings (which can't). So, your array will wind up holding references to existing functions or the actual functions themselves.
Based on your updated requirement that possible answers should also be shown along with the question, we need to rethink what you are storing in your array. Since a question will have associated possible answers, the best way to store each question with its answers is in an object. So, in the end, we will have an array of objects.
function q1(){ console.log("hello from q1"); }
function q2(){ console.log("hello from q2"); }
function q3(){ console.log("hello from q3"); }
function q4(){ console.log("hello from q4"); }
var randomFunctions = [q1, q2, q3, q4, function(){
console.log("hello from inline anonymous function.");
}];
var rand = randomFunctions[Math.floor(Math.random() * randomFunctions.length)];
rand();
Now, based on your use case, you really don't need or want to store an array of functions, you need to store an array of questions and then have one function that processes that randomly selected question. Like this:
// Get reference to HTML output area
var question = document.getElementById("questionArea");
var answer = document.getElementById("answerArea");
var btn = document.getElementById("btnGetQuestion");
// Set up button click event:
btn.addEventListener("click", showQuestion);
// Set up questions/answers array as an array of objects so that
// the questions and answers can be connected:
var qa = [
{
question:"What is your name?",
answers: ["Bob","Sally", "Mary", "Tim"]
},
{
question:"What is your favorite color?",
answers: ["Red","Green", "Blue", "Orange"]
},
{
question:"What is the average air speed of a laden swallow?",
answers: ["22 mph","18 mph", "17 kmh", "African or European?"]
}
];
// One function to process question:
function showQuestion(){
// Get a random number based on lenght of the questions array
var num = Math.floor(Math.random() * qa.length);
// Get a random object out of the array and extract the question from the object
question.textContent = qa[num].question;
// Loop over all the values in the "answers" object array
// and display them. Build up an output string as well
var html = "<form>";
qa[num].answers.forEach(function(answer, index){
html += "<input type='radio' name='q" + index + "' value='" + answer + "'>" + answer;
});
// close the string and display:
html += "</form>";
answer.innerHTML = html;
}
button {
margin:2em 0;
}
#answerArea {
margin: 1em 0 0 1em;
}
<div id="questionArea"></div>
<div id="answerArea"></div>
<button id="btnGetQuestion">Get A Question</button>

Unexpected Type Error - Javascript, multidimensional arrays

I'm learning to code Javascript. I'm trying to create a random quote generator. The idea is that I have a method that creates a multidimensional array, with each element array having a quote and the author's name. This method returns the multidimensional array.
I assign this returned multidimensional array to a variable and pick a random element array. It gives me an "Unexpected Type Error" in the console.
<script>
var colors = ['#16a085', '#27ae60', '#2c3e50', '#f39c12', '#e74c3c', '#9b59b6',
'#FB6964', '#342224', '#472E32', '#BDBB99', '#77B1A9', '#73A857'];
console.log("Hi!");
function getQuote(){
var quotesAndAuthors =
[
['But suicides have a special language. Like carpenters, they want to know "which tools", they never ask "why build"', "Anne Sexton"],
['Here is the world. Beautiful and terrible things will happen. Dont be afraid', 'Frederick Buechner'],
['All grown-ups were once children, but only a few of them remember it', 'Alexander de Saint-Exupery'],
['It was love at first sight, at last sight, at ever ever sight', 'Vladimir Nabokov'],
['A paradise the color of hell flames, but a paradise nonetheless', 'Vladimir Nabokov'],
['There is nothing like the deep breaths after laughing that hard. Nothing in the world like a sore stomach for the right reasons','Stephen Chbosky'],
['And then suddenly, something is over','Louise Gluck'],
['Adventure is out there!', 'Up (Pixar)'],
['The strong do what they can, and the weak suffer what the must', 'Thucydides'],
['But who prays for Satan? Who, in eighteen centuries, has had the common humanity to pray for the one sinner that needed it most?', 'Mark Twain'],
['I stopped explaining myself when I realized people only understand from their level of perception', 'Unknown'],
['Unexpressed emotions will never die. They are buried alive and will come forth in uglier ways', 'Sigmund Freud'],
['Genius might be the ability to say a profound thing in a simple way', 'Charles Bukowski']
];
return quotesAndAuthors;
}
function generate(){
var pickColor = Math.floor(Math.random * colors.length);
$('html body').animate({
backgroundColor: colors[pickColor]
}, 1000);
$('#text #author').animate({
color: colors[pickColor]
}, 500);
$('.buttons').animate({
backgroundColor: colors[pickColor]
},500);
var quotes = getQuote();
var n = Math.floor(Math.random * quotes.length);
var quoteText = quotes[n][0];
var quoteAuthor = quotes[n][1];
$('#text').text(quoteText);
$('#author').text(quoteAuthor);
}
$(document).ready(function(){
generate();
alert("Testing");
$('#quoteButton').on('click', generate());
});
</script>
Also, suggestions on how to store quotes more effectively would be appreciated.
random is a function and not a property. You should use paranthesis like
var n = Math.floor(Math.random() * quotes.length);
Also while adding event listeners, you should not use paranthesis, as this will call the method before even click event. Just give the function name.
$('#quoteButton').on('click', generate);
Also it's better to use arrary of objects in your case as below:
var quotesAndAuthors = [
{
"quote" : "But suicides have a special language",
"athour" : "Anne Sexton"
},
{
"quote" : "All grown-ups were once children",
"athour" : "Alexander de Saint-Exupery"
}
];
And you can access the quote as below using either of the method:
console.log(quotesAndAuthors[0]["quote"]);
console.log(quotesAndAuthors[0].quote);
.random is not a property of the Math object.
Math.random() is a method.
You wanted to call Math.random() because that's a function (note the parenthesis). That was generating your error.

Categories

Resources