I am trying to build a quote generator using an object instead of an array.
I am able to get results but instead of getting the quote, I am getting the name of the quote.
I tried using the bind method, however, there was no result.
Any help, please?
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Quote Generatr</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css">
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="text-center">
<div class="background">
<h1>2018 Reading Notes</h1>
<p>Motivational Quotes</p>
</div>
<p id="quotes"></p>
<button class='btn btn-danger mt-4' style="border-radius: 0px; font-size: 2rem;">Show me another Quote</button>
<p class="mt-5">Made with ❤️️ by Anthony</p>
</div>
<script src="jquery-3.3.1.min.js"></script>
<script src="script.js"></script>
</body>
</html>
var paragraph = document.querySelector('#quotes');
var butonGenerator = document.querySelector('.btn');
var quotes = {
quote1: {
author: 'Carol Burnett',
quote: 'Only I can change my life. No one can do it for me.'
},
quote2: {
author: 'Norman Vaughan',
quote: 'Dream Big and Date to Fail.'
},
quote3:{
author:'Jean-Claude Van damme',
quote:'I now truly belive it is impossible for me to make a bad movie.'
}
}
butonGenerator.addEventListener('click', quoteGenerator);
function quoteGenerator(){
var count = 0;
for(var value in quotes){
if(Math.random() < 1/count++)
paragraph.innerHTML = value;
console.log(value);
}
}
Somehow missed the part where you didn't want to use an array. But that is definitely the way to go. See below.
You should have an array of quotes. See below snippet. Put the javascript in <script></script> tags below the </body> tag
var paragraph = document.querySelector('#quotes');
var butonGenerator = document.querySelector('.btn');
var quotes = [
{
author: 'Carol Burnett',
quote: 'Only I can change my life. No one can do it for me.'
},
{
author: 'Norman Vaughan',
quote: 'Dream Big and Date to Fail.'
},
{
author:'Jean-Claude Van damme',
quote:'I now truly belive it is impossible for me to make a bad movie.'
}
]
butonGenerator.addEventListener('click', quoteGenerator);
function quoteGenerator(){
var item = quotes[Math.floor(Math.random()*quotes.length)];
console.log(item.author);
console.log(item.quote);
paragraph.innerHTML = 'Author:<br />' + item.author + '<br /><br />Quote:<br />' + item.quote;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Quote Generatr</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css">
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="text-center">
<div class="background">
<h1>2018 Reading Notes</h1>
<p>Motivational Quotes</p>
</div>
<p id="quotes"></p>
<button class='btn btn-danger mt-4' style="border-radius: 0px; font-size: 2rem;">Show me another Quote</button>
<p class="mt-5">Made with ❤️️ by Anthony</p>
</div>
<script src="jquery-3.3.1.min.js"></script>
<script src="script.js"></script>
</body>
</html>
I have no clue why are you trying to use an object in this case but if that's a must, you might find Object.keys(quotes) useful as it returns the actual keys (so in your case the 'quote1', 'quote2', etc.) of your object as an array.
Then you could create a random number, retrieve the given index from the array created here and use that string to access the object properties.
var array = Object.keys(quotes); // convert the object to an array of it's keys
var key = array[randomIndex]; // get a random key
var quoteObject = quotes[key]; // use it to access the property of the object.
(https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys)
Anyways you should always use an array in this case if you are able to.
Related
I am getting a new array element from an input and adding to array but I can not print every element in a new row. I can print all elements of array in one row but can not print every element in a different row. I am using <br> after array name but does not work. What is your solution? It is like a todo list project.
var allmembers = [""];
function addnewmember() {
var newmemberr = document.getElementById("newmember").value;
allmembers.push(newmemberr);
for (var i = 0; i < allmembers.length; i++) {
document.getElementById("membername").innerHTML = allmembers[i] + "<br>";
}
}
<html>
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="stil.css">
</head>
<body>
<input id="newmember" placeholder="NEW MEMBER"><br>
<button type="button" onclick="addnewmember()">SEND</button>
<div id="members">MEMBERS</div>
<div id="membername"></div>
</body>
</html>
Your solution is appending a <br> to the end of the array, rather than between array items. Instead of looping over the array, just use the .join() method, which is ideal for something like this.
Additionally, using innerHTML in a loop is a big performance "no no" as it causes the browser to have to repaint and possibly reflow the DOM document repeatedly. In such cases, you should build up a string that contains the HTML you want and after the loop is done set that string as the innerHTML of the desired element in one single command. And really, the use of innerHTML should be avoided if at all possible because of security concerns as well.
See additional comments inline:
let allmembers = [];
// Get your DOM references just once, not every time the function runs
// Make references to DOM elements, rather than their propreties. This
// way, if you decide you need access to a different DOM element property
// you don't have to scan for the element again.
let newmember = document.getElementById("newmember");
let memberName = document.getElementById("membername");
function addnewmember() {
allmembers.push(newmember.value);
newmember.value = ""; // Clear out the input
// No need for a loop. Just join the arry elements
// with a <br> between them.
memberName.innerHTML = allmembers.join("<br>");
}
<html>
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="stil.css">
</head>
<body>
<input id="newmember" placeholder="NEW MEMBER"><br>
<button type="button" onclick="addnewmember()">SEND</button>
<div id="members">MEMBERS</div>
<div id="membername"></div>
</body>
</html>
I am trying to make a simple latin dictionary. I am new to JavaScript so I am trying to test the input tag with the alert function. In the console, I am receiving the error message after I click the "translate" button. Error: "translate is not a function (in 'translate()', 'translate' is true)".
HTML:
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="style.css">
<title>Latin Dictionary</title>
</head>
<h1 id="main-header">Latin Dictionary!</h1>
<body>
<input id="latin-word" placeholder="Latin to English"/>
<br />
<button onclick="translate()" id="btn-translate-latin-english">Translate</button>
<script type="text/javascript" src="translate.js"></script>
</body>
</html>
JavaScript:
function translate() {
var latinWord = document.getElementById("latin-word").value;
alert("word that was entered: " + latinWord);
}
Thank you in advance :)
To solve it, choose another function name, such as myTranslate().
Why you can't use translate()? Because there's already a built-in translate in HTML. See here.
Note: You can choose whatever you want.
JS Code:
function myTranslate() {
var latinWord = document.getElementById("latin-word").value;
alert("word that was entered: " + latinWord);
}
HTML:
<button onclick="myTranslate()" id="btn-translate-latin-english">Translate</button>
Let me know if it works.
I think this error is being called because you are using the script tag after the button tag. I think moving the script into the head of the html will solve the issue
You seem to use the function's name translate which is a reserved word in JavaScript.
translate is a global attribute to make elements translatable or movable.
You must rename the function to fix this error. I used Translate():
function Translate() {
var latinWord = document.getElementById("latin-word").value;
alert("Word that was entered: " + latinWord);
}
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="style.css">
<title>Latin Dictionary</title>
</head>
<h1 id="main-header">Latin Dictionary!</h1>
<body>
<input id="latin-word" placeholder="Latin to English"/>
<br />
<button onclick="Translate()" id="btn-translate-latin-english">Translate</button>
<script type="text/javascript" src="translate.js"></script>
</body>
</html>
I am making a clicker game. When I display the moneyCurrent variable I get incorrect numbers. The numbers don't actually join. This is in the sellTech() function.
If you want the full project go to enter link description here techClicker
This is on repl.it and that is not the problem.
I have tried parseInt() and Number() and the numbers keep adding like
they are strings.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>Tech Clicker</title>
<link rel="shortcut icon" type="image/png" href="IMAGE"/>
<link href="techClicker.css" rel="stylesheet" type="text/css" />
</head>
<body>
<h1>Tech Clicker</h1>
<h2 id="moneyValueText">$0</h2>
<div id="ccDiv">
<input id="ccMakeButton"type="image" src="IMAGE"
onclick="ccClickFunc()" width="50"
height="50">
<p> </p>
<button id="ccSellButton"onclick="sellTech()">Sell Computer
Chips</button>
<h4 id="ccCounter">Computer Chips = </h4>
</div>
<div id="usbDiv">
<input id="mcMakeButton"type="image"
src="IMAGE"
onclick="mcClickFunc()" width="38"
height="26">
<p> </p>
<button id="mcSellButton"onclick="sellTech()">Sell Memory Chips</button>
<h4 id="mcCounter">Memory Chips = </h4>
</div>
<script src="clickGainFunc.js"></script>
<script src="sellTechV2.js"></script>
</body>
</html>
var ccPrice = 0.25
var ccSellAmount
var mcPrice = 0.35;
var mcSellAmount;
//JAVASCRIPT
function sellTech(){
ccSellAmount = cc * ccPrice;
mcSellAmount = mc * mcPrice;
moneyCurrent = ccSellAmount + mcSellAmount;
document.getElementById("moneyValueText").innerHTML = moneyCurrent;
cc = 0;
mc = 0;
document.getElementById("ccCounter").innerHTML = "Computer Chips = " + cc;
document.getElementById("mcCounter").innerHTML = "Memory Chips = " + mc;
}
I expected that the numbers would add up and not drop in value.
This is a little hard to explain so go to
https://techclicker--beraemirkoklu.repl.co/
and then click on the computer chip once. And then sell it. 0.25. If you sell 2, 0.5. if you sell 1, again .25. I am trying to fix that too.
Why won't the text inside the tags change, when it clearly should change? Can anyone help?
Here is my HTML and JS code:
function pickStick(); {
weapon = "Stick";
weapondamage = 1;
document.getElementById("weapon").innerHTML = "Weapon: ";
}
And...
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="script.js"></script>
<link rel="stylesheet" type="text/css" href="main.css">
</head>
<body>
<br><br>
<div id="weapon">You see a stick. You can pick it up.</div>
</body>
</html>
You have a semicolon after your function name ( function pickStick(); ), you need to remove that:
function pickStick() {
weapon = "Stick";
weapondamage = 1;
document.getElementById("weapon").innerHTML = "Weapon: ";
}
Then you may want to remove the href from your <a> so it doesn't move to a new page, or replace it with href="#":
pick it up.
You need to update 2 things
JS update
Replace
function pickStick(); {
with
function pickStick() {
Markup update
Replace
<a href="" onclick="pickStick()">
with
<a href="#" onclick="pickStick()">
or
<a href="javascript:void(0);" onclick="pickStick()">
For reference - http://plnkr.co/edit/wu1y9OA1Ml1gQPCEQImB?p=preview
This works:
function pickStick() {
weapon = "Stick";
weapondamage = 1;
document.getElementById("weapon").innerHTML = "Weapon: ";
}
<div id="weapon">You see a stick. You can pick it up.
So the problem is probably due to you having a semi-colon in your function definition, or the missing pound sign (#) in your anchor.
I have a problem with simple thing.
I want to add a element into html div tag using createElement Method. I have tried a lot of diferent ways but always getting the same result - nothing happens.
This is my code:
function changeReleaseDate()
{
var parentElement = document.getElementByClassName("container body-content");
var existingElement = document.getElementByClassName("btn btn-default");
var newInput = document.createElement("input");
newInput.type = "text";
newInput.className = "form-control";
parentElement.insertBefore(newInput, existingElement);
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>My ASP.NET Application</title>
<link href="~/Content/Site.css" rel="stylesheet" type="text/css" />
<script src="script.js"></script>
</head>
<body>
<div class="container body-content">
<h2>Index</h2>
<button id="btn" type="button" onclick="changeReleaseDate()" class="btn btn-default">Default</button>
<hr />
<footer>
<p>©My ASP.NET Application</p>
</footer>
</div>
</body>
</html>
I also tried to use appendChild but in this case input field was placed out of div.
The problem is that getElementByClassName should be getElementsByClassName.
This method returns a HTMLCollection, so to access the first element from this list you need to use bracket with index 0:
var parentElement = document.getElementsByClassName("container body-content")[0];
var existingElement = document.getElementsByClassName("btn btn-default")[0];
Demo: http://jsfiddle.net/jak4efau/
However it's more convenient in your case to use querySelector method:
var parentElement = document.querySelector(".container body-content");
var existingElement = document.querySelector(".btn.btn-default");
Also note, that you need to take care of the case when user clicks button multiple times, you probably don't want to append multiple input fields.