I'm building a random quote machine for Free Code Camp. I need to have one button that produces a random quote and another button that post one of the random quotes to twitter. My random quote button seems to be working fine. I've started work on the twitter button but have run into a road block right away. I'm trying to store that value of the "p" element, i.e. the quote, into a variable so I can use it to build the rest of the button. I tried to log the value of the element just to see if it worked but it returns "undefined" whether there is a quote present or not. I've tried to manipulate the document.getElementById().value method a bunch of different way but can't seem to get it to return a string. Any insight into why its only returning undefined would be helpful. Thank You!
This is my HTML
<!DOCTYPE html>
<html lang="en">
<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>Random Quote Machine</title>
<link rel="stylesheet" style="text/css" href="main.css">
</head>
<body>
<div class="main-header">
<h1>Random Quote Machine</h1>
</div>
<div class="main-content" id="main-content">
<p class="text" id="text"></p>
</div>
<button type="submit" class="quote-button" id="quote-button">New Quote</button>
<button type="submit" class="twitter-button" id="twitter-button">Twitter</button>
<script type="text/javascript" src="script.js"></script>
</body>
</html>
This is my Javascript so far
const btn = document.getElementById('quote-button');
const content = document.getElementById('text');
let strValue = document.getElementById('text').value;
const twitter = document.getElementById('twitter-button');
// New Quote Button Event Listener
btn.addEventListener('click', function () {
var xhr = new XMLHttpRequest();
xhr.open('GET', 'http://api.forismatic.com/api/1.0/?method=getQuote&format=json&lang=en');
xhr.onload = function () {
var data = JSON.parse(xhr.responseText);
const quote = data.quoteText + data.quoteAuthor;
getQuote(quote);
};
xhr.send();
});
function getQuote(newQuote) {
content.textContent = newQuote;
}
// Twitter Button Event Listener
twitter.addEventListener('click', function () {
console.log(strValue);
});
In my code, I updated the Quote Text and The Author name using a function and used those variables when I wanted to share the tweet.
Hope that helps!
HTML:
<div class= "container">
<div class="card bg-dark text-white">
<img class="card-img" src="https://static1.squarespace.com/static/5ab008d6697a9880a9f8c364/t/5abc6961aa4a99a0ab790df2/1522693072256/background-for-quotes-5.jpg" alt="Card image">
<div class="card-img-overlay">
<h5 class="card-title">Quote of the day!</h5>
<blockquote class="blockquote mb-0">
<p id ="quote" class="card-text"></p>
<p id ="author" class="card-text"></p>
<button id = "quote_button" type="button" class="btn btn-secondary" >Click me to get a quote</button>
<a id = "tweet_btn" ><button type="button" class="btn btn-secondary">
Tweet the quote </button>
</a>
</div>
</blockquote>
</div>
</div>
</div>
JS :
var jd;
var currentQuote;
var currentAuthor;
var data = {
method: "getQuote",
lang: "en" ,
format:"jsonp",
dataType: "jsonp"
};
var texttotweet;
$("#quote_button").on("click", function(){
// Only change code below this line.
getthequote();
console.log(currentQuote);
});
function getthequote() {
$.getJSON("http://api.forismatic.com/api/1.0/?method=getQuote&format=jsonp&lang=en&jsonp=?", data, function(jd) {
$('#quote').html('<p>'+ jd.quoteText + '</p>');
$('#author').html('<p>-' + jd.quoteAuthor + '</p>');
quotedata(jd.quoteText , jd.quoteAuthor );
});
}
function quotedata(quote, author )
{
currentQuote = quote;
currentAuthor = author;
}
$('#tweet_btn').on("click", function(){
$(this).attr("href", "https://twitter.com/intent/tweet?text=" + "The Quote:" + currentQuote + ". The Author :" + currentAuthor );
console.log("Testing out the code");
});
A p element doesn't have a value attribute. Try innerHTML...
Related
I am making a project about add to cart. I want to pass event by onclick from innerhtml.
Here is my html code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Add to cart</title>
<link
href="https://cdn.jsdelivr.net/npm/bootstrap#5.0.2/dist/css/bootstrap.min.css"
rel="stylesheet"
integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC"
crossorigin="anonymous"
/>
</head>
<body>
<div id="cards-container" class="row align-items-center my-3 p-3"></div>
<script src="./script.js"></script>
</body>
</html>
Here is my js code
fetch('https://jsonplaceholder.typicode.com/users')
.then(res=>res.json())
.then(data=>show(data))
function show(data){
const cardsContainer = document.getElementById('cards-container');
cardsContainer.innerHTML='';
data.map(element => {
const cardDiv = document.createElement('div')
cardDiv.className= "col-md-4"
cardDiv.innerHTML=`
<div class='card p-5 m-1'>
<h3>${element.name}</h3>
<h5>${element.email}</h3>
<button class="btn btn-primary" id='card-button' onclick='setLocalStorage(e)'>Add to Card</button>
</div>
`
cardsContainer.appendChild(cardDiv);
});
}
function setLocalStorage(e){
console.log("clicked",e)
}
I got this error in console https://d.pr/i/JCjI77
I've run into this issue a few times before as well.
First, I would suggest using jquery anyway. When writing plain html, I almost always use jquery. It makes interaction with the DOM much easier. So here is an example in jquery of the onClick event for an element with id="card-button". A normal click event won't work from jquery here. You have to set it on the document and then further set a selector:
fetch('https://jsonplaceholder.typicode.com/users')
.then(res=>res.json())
.then(data=>show(data))
function show(data){
const cardsContainer = $('#cards-container');
cardsContainer.html("");
data.map(element => {
cardsContainer.append(`
<div class='card p-5 m-1 col-md-4'>
<h3>${element.name}</h3>
<h5>${element.email}</h3>
<button class="btn btn-primary" id='card-button'>Add to Card</button>
</div>
`
});
}
$(document).on("click", "#card-button", function(e) {
setLocalStorage(e)
// or you can just place the contents of setLocalStorage directly
// into here!
})
function setLocalStorage(e){
console.log("clicked",e)
}
you can remove onClick from the button element here. Make sure you remember to import jquery. Ideally the minified version.
BUT YOU HAVE ANOTHER MORE IMPORTANT ISSUE
you're creating multiple add card buttons with the same id (card-button). you need to set card-button as a class. This way it can be applied multiple elements. I would suggest adding an ID to the button or cardDiv that is associated with userID, Index or any other unique identifier. This way you can recognize which user or card button is actually being pressed, and take action accordingly. Here is the updated jQuery with class instead of ID
fetch('https://jsonplaceholder.typicode.com/users')
.then(res=>res.json())
.then(data=>show(data))
function show(data){
const cardsContainer = $('#cards-container');
cardsContainer.html("");
data.map(element => {
cardsContainer.append(`
<div class='card p-5 m-1 col-md-4'>
<h3>${element.name}</h3>
<h5>${element.email}</h3>
<button class="btn btn-primary" class="card-button" id='some-unique-id'>Add to Card</button>
</div>
`
});
}
$(document).on("click", ".card-button", function(e) {
setLocalStorage(e)
// or you can just place the contents of setLocalStorage directly into here!
// Here you can grab the jquery object with $(this), or use the
// ID with e.target.id with the e.target.id, etc...
clickedButton = $(this);
clickedButtonID = e.target.id;
})
function setLocalStorage(e){
console.log("clicked",e)
}
I don't use plain HTML without jQuery often, so I can't answer for sure if you want to take that route. It seems as if this previous thread answers that question, definitely better than I could.
unable to use getElementById on HTML element not yet appended to document
Best of luck!!
this is my code:
"use strict";
const searchBox = document.querySelector("#myText");
const searchBtn = document.querySelector(".btn-search");
const searchContainer = document.querySelector(".search-container");
let mainText = document.querySelector(".main-text");
const quit = document.querySelector("#btn-close");
let showMain;
const newMain = "";
let printMain = function(text) {
showMain = `
<article class="country">
<h1>Country you Searched</h1>
<p>Hello</p>
<p>${text}</p>
</article>`;
console.log(`Our show main is : ${showMain}`);
mainText.insertAdjacentHTML("beforeend", showMain);
};
searchBox.addEventListener("click", function() {
if (searchBox.value === "Type in") {
searchBox.value = "";
}
});
searchBtn.addEventListener("click", function() {
if (searchBox.value && searchBox.value !== "Type in") {
console.log(searchBox.value);
printMain(searchBox.value);
searchBox.value = "";
} else {
alert("please type in country name!");
}
});
quit.addEventListener("click", function() {
//mainText.remove(showMain);
const myDiv = document.getElementById("myId");
const parent = myDiv.parentNode;
parent.removeChild(myDiv);
console.log(showMain);
});
<!DOCTYPE html>
<html lang="en">
<header>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<script defer src="script.js"></script>
<title>Simple Work</title>
<button id="btn-close">go back</button>
</header>
<body>
<main class="container">
<div class="main-text" id="myId"></div>
<p class="search-container">
<label>Type In : </label>
<input type="text" id="myText" value="Type in" />
</p>
<button class="btn-search">input</button>
</main>
</body>
</html>
So, I was trying to make code that add the text using insertAdjacentHTML
and next when I click "go back" button, it will erase the html that I had added using insertAdjacentHTML.
I have success up to this point. After this when I try to add new HTML using insertAdjacentHTML, it doesn't work. What I must do to fix this?
(as my English is second language, explanation might not be clear, I am just making web site that I could add text(must use insertAdjacentHTML) and erase that by using "go back" button and after I erase all of them, it could add new text again by using "input" button)
When you remove the node, you are removing the element that mainText points to, therefore, you code cannot place content into a node that is no longer there. So it throws an error stating so.
You should probably only remove the element with classname of country:
document.querySelector('.country').remove();
When I run my code and press either the button 'encode' or the button 'decode' I get this error:
Uncaught ReferenceError: value1 is not defined
at HTMLButtonElement.onclick (HtmlPage2.html:34)
I have tried to move the script as an external file to the area above the </body> but I still get the same.
It seems that value1 is not recognized at the input as the 'name'. Shouldn't that get it defined?
Shortly:
I don't understand why value1 is undefined. Could someone please explain?
This is my code :
var newURL;
function setEncode(myURL) {
newURL = encodeURIComponent(myURL);
alert(newURL);
document.getElementById("info").innerHTML = newURL.toString();
}
function setDecode(myURL) {
decodeURL = decodeURIComponent(newURL);
alert(decodeURL);
document.getElementById("info").innerHTML = decodeURL.toString();
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
</head>
<body>
<input type="text" name="value1" />
<button name="encode" onclick="setEncode(value1.value)"> encode </button>
<button name="decode" onclick="setDecode(value1.value)"> decode </button>
<div id="info"> Decode / encode </div>
</body>
</html>
Thank you all!
Use id instead of name attribute.
var newURL;
function setEncode(myURL) {
newURL = encodeURIComponent(myURL);
document.getElementById("info").innerHTML = newURL.toString();
}
function setDecode(myURL) {
decodeURL = decodeURIComponent(newURL);
document.getElementById("info").innerHTML = decodeURL.toString();
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
</head>
<body>
<input type="text" id="value1" />
<button name="encode" onclick="setEncode(value1.value)"> encode </button>
<button name="decode" onclick="setDecode(value1.value)"> decode </button>
<div id="info"> Decode / encode </div>
</body>
</html>
Reason behind this:
If an html element assigned ID attribute, it can be used in javascript with that variable name. For example
myDiv.innerHTML = myDiv.innerHTML + "<p>See? What did I tell you?</p>";
<div id="myDiv">
This div ID is myDiv, can be called in JavaScript.
</div>
You can't assign the values directly to the function in your html. But you can can use selectors to get the value from input and attach an event listener to your button However if you you want to do all this on the html you do something like this
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
<script>
// encoding and decoding URIs
var newURL;
function setEncode(myURL) {
newURL = encodeURIComponent(myURL);
alert(newURL);
document.getElementById("info").innerHTML = newURL.toString();
}
function setDecode() {
decodeURL = decodeURIComponent(newURL);
alert(decodeURL);
document.getElementById("info").innerHTML = decodeURL.toString();
}
</script>
</head>
<body>
<input type="text" id="value1" />
<button name="encode" onclick="javascript:(function (){let v=document.getElementById('value1');setEncode(v.value)})()"> encode </button>
<button name="decode" onclick="javascript:(function (){let v=document.getElementById('value1');setEncode(v.value)})()"> decode </button>
<div id="info"> Decode / encode </div>
</body>
</html>
I am working on an assignment in which I need to create javascript code to allow a user to input something and have it be appended to an array. This is the HTML:
<html lang="en">
<head>
<title>Magic 8 Ball!</title>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="css/style.css">
</head>
<body>
<div class="container">
<h1>Magic 8 ball</h1>
<h2>Ask your question, then click on the button!</h2>
<div class="eightBall">
<div id="output">
<p id="result">8</p>
</div>
</div>
<div class="inpBox">
<input type="text" id="inputBox"></input>
</div>
<div class="buttons">
<button id = "addButton" type="button">Add</button>
<button type="button">Custom</button>
<button id = "defaultButton" type="button">Default</button>
<button id = "Ask" type="button">Ask</button>
</div>
</div>
</body>
<script src="js/main.js"></script>
</html>
And the Javascript:
console.log(defaultList)
var customList = [""]
var inputText = document.getElementById("inputBox")
console.log(customList);
document.getElementById("addButton").addEventListener("click", function(){
customList.push(inputText);
console.log(customList);
});
Everything is working properly except when I check the console log to see what value the customList has, it brings the actual input box itself and not the text inside of it.
An image of the console log:
https://imgur.com/a/AiV4hRM
I just need the user to input some text which I will append to an empty array. It isn't taking the text that the user inputted, instead taking the actual input box.
You need to get the value of the input from value attribute.
The below code will just return the reference to the input not the value.
var inputText = document.getElementById("inputBox");
To get the value of the input, you need to get it from the value attribute.
var inputText = document.getElementById("inputBox");
console.log(inputText.value);
Working Example:
let customList = []
let inputText = document.getElementById("inputBox")
console.log(customList);
document.getElementById("addButton").addEventListener("click", function() {
let inputValue = inputText.value;
if (inputValue) {
customList.push(inputValue);
console.log(customList);
}
});
<input type="text" id="inputBox">
<button type="button" id="addButton">Click me</button>
You are pretty close, just missing that you need to get the value attribute of the textbox. See working example below.
var customList = [""]
var inputText = document.getElementById("inputBox")
console.log(customList);
document.getElementById("addButton").addEventListener("click", function(){
customList.push(inputText.value);
console.log(customList);
});
<input id="inputBox" />
<button id="addButton">Add</button>
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.