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);
});
2
Answers
A p element doesn’t have a value attribute. Try innerHTML…
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:
JS :