quote generator without repeating not working - javascript

Hi I want to use the RandomQuoteGenerator Script and I found one on stackoverflow but I want it to not repeat the quotes, I found a solution here but it is not working for me. I am getting undefined error when clicking on the button. The original script provided in the above link is working fine but if I change the function as mentioned in the above link, I am getting undefined messages instead of quotes.
My Generator.js
var quotes = [
//success quotes
{
quote: "If you set your goals ridiculously high and it's a failure, you will fail above everyone else's success.",
source: "James Cameron",
tag: "success"
},
{
quote: "The Way Get Started Is To Quit Talking And Begin Doing",
source: "Walt Disney",
tag: "success"
},
{
quote: "Don’t Let Yesterday Take Up Too Much Of Today.",
source: "Will Rogers",
tag: "success"
},
{
quote: "We Generate Fears While We Sit. We Overcome Them By Action",
source: "Dr. Henry Link",
tag: "success"
},
//health quotes
{
quote: "Early to bed and early to rise, makes a man healthy wealthy and wise.",
source: "Benjamin Franklin",
tag: "health"
},
{
quote: "Let food be thy medicine and medicine be thy food.",
source: "Hippocrates",
tag: "health"
},
{
quote: "If you can’t pronounce it, don’t eat it.",
source: "Common Sense",
tag: "health"
},
{
quote: "Health is like money, we never have a true idea of its value until we lose it.",
source: "Josh Billings",
tag: "health"
},
//spirituality quotes
{
quote: "Life is really simple, but men insist on making it complicated.",
source: "Confucius",
tag: "spirituality"
},
{
quote: "My religion is very simple. My religion is kindness.",
source: "Dalai Lama",
tag: "spirituality"
},
{
quote: "Knowing others is wisdom; knowing the self is enlightenment.",
source: "Tao Te Ching",
tag: "spirituality"
},
{
quote: "When there is love in your heart, everything outside of you also becomes lovable.",
source: "Veeresh",
tag: "spirituality"
}
];
document.getElementById('loadQuote').addEventListener("click", printQuote, true);
//Sets up interval to show print qutoe every 15 seconds
var intervalID = window.setInterval(myCallback, 15000);
function myCallback() {
printQuote();
}
// Gets a random quote from array Quotes
function getRandomQuote () {
return quotes.splice(Math.floor(Math.random() * quotes.length), 1);
}
//prints quote to html
function printQuote() {
var getQuote = getRandomQuote();
var message = '';
message += '<p class ="quote">' + getQuote.quote + '</p>';
message += '<p class ="source">' + getQuote.source + '</p>';
message += '<p class ="tag">' + getQuote.tag + '</p>';
document.getElementById('quote-box').innerHTML = message;
newColor();
}
// function that will generate random color to the backgroun
var newColor = function randomColor() {
document.body.style.background = '#'+(Math.random()*0xFFFFFF<<0).toString(16);
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Random Quotes</title>
<link href='https://fonts.googleapis.com/css?family=Playfair+Display:400,400italic,700,700italic' rel='stylesheet' type='text/css'>
<link rel="stylesheet" href="css/normalize.css">
<link rel="stylesheet" href="css/styles.css">
</head>
<body>
<div class="container">
<div id="quote-box">
<p class="quote">Be the change you wish to see in the world! </p>
<p class="source">Ghandi </p>
</div>
<button id="loadQuote">Show another quote</button>
</div>
<script src="quotes.js"></script>
<script src="generate.js"></script>
</body>
</html>

Your function getRandomQuote() returns an array so in order to access the object you need to access the first element of that array. Like this...
getQuote[0].quote

Related

Need advice on getting my code to work (linking a javascript function to an html element)

I'm playing around with linking JavaScript to HTML and creating event listeners and I stumbled upon an issue with my code.
HTML:
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>Quote randomizer</title>
</head>
<body>
<p id="switchy">Click me</p>
</body>
<script src="script.js"> </script>
</html>
JavaScript
const sentences = ["I am the first sentence", "Second sentence reporting in", "I am the third one", "Hello there"];
const randomIndex = Math.round(math.random()*3);
function clicky() {
document.getElementById("switchy").innerHTML = "sentences[randomIndex]"";
}
document.getElementById("switchy").addEventListener("click", clicky);
What I want from it is to replace the text that's already written in HTML with a random string from a premade array, through a random function . However, I'm not sure what I'm doing wrong and why it's not working.
Found two problems:
Math !== math
Do not put quote marks around a variable
const sentences = ["I am the first sentence", "Second sentence reporting in", "I am the third one", "Hello there"];
const randomIndex = Math.round(Math.random()*3);
function clicky() {
document.getElementById("switchy").innerHTML = sentences[randomIndex];
}
document.getElementById("switchy").addEventListener("click", clicky);
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>Quote randomizer</title>
</head>
<body>
<p id="switchy">Click me</p>
</body>
<script src="script.js"> </script>
</html>
You're math.random() needs to be Math.random(). Move randomIndex into the click() function, so it randomizes on each click of "Click Me". Also, document.getElementById("switchy").innerHTML = "sentences[randomIndex]""; should be document.getElementById("switchy").innerHTML = sentences[randomIndex]; No quotes around the array variable. I added an additional paragraph element so you can see the sentences randomly appear on clicking of "Click Me".
const sentences = ["I am the first sentence", "Second sentence reporting in", "I am the third one", "Hello there"];
function clicky() {
let randomIndex = Math.round(Math.random() * 3);
document.getElementById("sentence-text").innerHTML = sentences[randomIndex];
}
document.getElementById("switchy").addEventListener("click", clicky);
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>Quote randomizer</title>
</head>
<body>
<p id="sentence-text"></p>
<p id="switchy">Click me</p>
</body>
</html>
This uses a functioncall to get the random number. I'm assuming that you want 0, 1, 2 and 3 to be possible results since the array contains 4 elements.
function getRandomInt(max) {
return Math.floor(Math.random() * Math.floor(max));
}
const sentences = ["I am the first sentence", "Second sentence reporting in", "I am the third one", "Hello there"];
function clicky() {
document.getElementById("switchy").innerHTML = sentences[getRandomInt(3)];
}
document.getElementById("switchy").addEventListener("click", clicky);
<p id="switchy">Click me</p>

referencing an object literal to set innerHTML in a span element javascript

I have a small data store of quotes like this:
let quotes = [{
quote: "Search others for their virtues, thyself for thy vices.",
source: "Benjamin Franklin",
citation: "Poor Richard\'s Almanac",
category: "ethics",
year: ''
}, {
quote: "He who has courage despises the future.",
source: "Napoleon Bonaparte",
citation: '',
category: "boldness",
year: ''
}
]
I am running a simple javascript function to change the html based on the data store with this:
const getRandomQuote = () => {
let quoteShownArr = [];
let quoteIndex = Math.floor((Math.random() * quotes.length) + 1);
for (let i = 0; i < quotes.length; i++) {
if (quoteIndex === i) {
document.getElementsByTagName("P")[0].innerHTML = quotes[i].quote;
document.getElementsByTagName("P")[1].innerHTML = quotes[i].source;
let citation = quotes[i].citation;
if(citation) {
console.log(citation);
document.getElementById("citation").innerHTML = quotes[i].citation;
}
document.getElementById("year").innerHTML = quotes[i].year;
}
}
}
getRandomQuote();
All the html elements are being updated except for my citation and year, which are span elements. I get the following error:
TypeError: "Cannot set property 'innerHTML' of null
at getRandomQuote" But the exact value consoles easily. How is this not changing the element??
Thanks.
HTML added:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Random Quotes</title>
<link href='https://fonts.googleapis.com/css?family=Playfair+Display:400,400italic,700,700italic' rel='stylesheet' type='text/css'>
<link rel="stylesheet" href="css/normalize.css">
<link rel="stylesheet" href="css/styles.css">
</head>
<body>
<div class="container">
<div id="quote-box">
<p class="quote">You can do anything but not everything</p>
<p class="source">David Allen<span class="citation" id="citation">Making It All Work</span><span class="year" id="year">2009</span></p>
</div>
<button id="loadQuote">Show another quote</button>
</div>
<script src="js/script.js"></script>
</body>
</html>
in this line
document.getElementsByTagName("P")[1].innerHTML = quotes[i].source;
you set the inner html to the source text, removing all other html content e.G your spans, this is why they are null because they dont exist anymore

How to read object properly in JavaScript

I am new to programming and recently began learning Javascript, I have a problem that appeared in few exercises that I made. I searched the site for more information but have not found a solution for my problem. I apologize in advance for my bad english and if this is not the right place or the right way to ask this question because this is my first post in Stackoverflow.
Currently practicing HTML templates. Assuming that the code is correct, I'm not sure where I'm wrong. Loading code into the browser and Handlebars gives me an error: "Error: You must pass a string or Handlebars AST to Handlebars.compile. You passed undefined". I tried to debug and saw that when I tried to take a value from date object it gives back undefined. In previous exercise had a similar problem in which I tried to read JSON object and did not manage to parse it and returned again undefined. Can you help me, I am stuck on this problem for some time.
var data = {
animals: [{
name: 'Lion',
url: 'https://susanmcmovies.files.wordpress.com/2014/12/the-lion-king-wallpaper-the-lion-king-2-simbas-pride-4685023-1024-768.jpg'
}, {
name: 'Turtle',
url: 'http://www.enkivillage.com/s/upload/images/a231e4349b9e3f28c740d802d4565eaf.jpg'
}, {
name: 'Dog'
}, {
name: 'Cat',
url: 'http://i.imgur.com/Ruuef.jpg'
}, {
name: 'Dog Again'
}]
}
window.onload = function() {
var htmlTemplate = document.getElementsByClassName('container-template').innerHTML;
var template = Handlebars.compile(htmlTemplate);
for (let x of data.animals) {
if (x.hasOwnProperty('url')) { //x.url
x.hasUrl = true;
} else {
x.hasUrl = false;
}
}
document.getElementsByClassName('container').innerHTML = template(data);
}
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Animals & Batman</title>
</head>
<body>
<div class="container">
</div>
<script class="container-template" type="text/x-handlebars-template">
<h1>Animals</h1>
{{#each animals}}
{{#if hasUrl}}
<li>
See a {{name}}
</li>
{{else}}
<li>
No link for {{name}}, here is Batman!
</li>
{{/if}}
{{/each}}
</script>
<script src="../handlebars-v4.0.5.js" charset="utf-8"></script>
<script src="../jquery-3.1.0.js" charset="utf-8"></script>
<script src="./main.js" charset="utf-8"></script>
</body>
</html>
document.getElementsByClassName returns an array of elements, not a single one - since multiple elements on a page can have the same class.
What you probably want is to use the id instead of class:
<script id="container-template" type="text/x-handlebars-template">
var htmlTemplate = document.getElementById('container-template').innerHTML;

Show hidden div after so many seconds breaks code?

setTimeout breaks code what I want to do if after a random text and image has been choosen (that works)
I have a div called quote where the random text and image goes and i want that to fade in say like in 3 seconds time ....
But it just isnt working Im a nooby so any help would be great heres the code I have so far:
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>Random</title>
<script src="jquery-2.1.1.min.js"></script>
</head>
<body>
<div id="quote"></div>
<script>
(function() {
var quotes = [
{
text: "text1",
img: "http://i.stack.imgur.com/FqBE6.jpg?s=32&g=1"
},
{
text: "text2",
img: "https://www.gravatar.com/avatar/ca3e484c121268e4c8302616b2395eb9?s=32&d=identicon&r=PG",
},
{
text: "text3",
img: "https://www.gravatar.com/avatar/ca3e484c121268e4c8302616b2395eb9?s=32&d=identicon&r=PG",
}
];
var quote = quotes[Math.floor(Math.random() * quotes.length)];
document.getElementById("quote").innerHTML =
'<p>' + quote.text + '</p>' +
'<img src="' + quote.img + '">';
})();
$('#quote').hide();
setTimeout(function(){
$('#quote').show();
$('#quote').fadeIn(1000);
}, 3000);
</script>
</body>
</html>
I also want the quote div to be hidden at 1st hide();
any idea's ? thanks.
If you remove $('#quote').show(); from your setTimeout, it will fade in properly.
setTimeout(function(){
$('#quote').fadeIn(1000);
}, 3000);

jQuery template not showing data elements

I'm trying to get the jQuery template feature working but have finally come to a dead end. From all my investigation the code listing below should work and I expect to get:
file1.txt, 123456, 2012-01-01
file2.txt, 234567, 2012-01-02
file3.txt, 345678, 2012-01-03
but instead I get
, ,
, ,
, ,
Clearly the library is loading and the code is running but for some reason it will not pick up the data elements. The code behaves the same regardless of the browser. I've tried compiling the template and not, each with the same results.
I'm sure that I'm missing something simple, but I've been pulling my hair out for about 8 hours staring at examples (and I've not that much hair left!). Thanks in advance for any assistance.
<html lang="en">
<head>
<title>jQuery Template Test</title>
<script src="http://code.jquery.com/jquery.min.js" type="text/javascript"></script>
<script src="inc/jquery.tmpl.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function() {
var exampleData = [
{ name: "file1.txt", size: "123456", date: "2012-01-01" },
{ name: "file2.txt", size: "234567", date: "2012-01-02" },
{ name: "file3.txt", size: "345678", date: "2012-01-03" }
];
var markup = "<li>${name}, ${size}, ${date}</li>";
$.template( "exampleTemplate", markup );
$.tmpl("exampleTemplate", exampleData).appendTo("#target");
});
</script>
</head>
<body>
<ul id="target"></ul>
</body>
</html>
I had the same problem with JSP: Use \$ to escape EL expression

Categories