Skip to content

Instantly share code, notes, and snippets.

@pmheintz
Created April 2, 2018 22:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pmheintz/8faa16e7e65ba7592815767870bcb77c to your computer and use it in GitHub Desktop.
Save pmheintz/8faa16e7e65ba7592815767870bcb77c to your computer and use it in GitHub Desktop.
Random quote generator with get new quote and tweet buttons.
// Object to hold quotes and authors
var myObj = null;
// Indexes for current quote and new quote so same quote isn't repeated back to back
var randQuote = 0;
var newQuote = 0;
$(document).ready(function() {
// Get a quote
getQuote();
// On click listener on element with id of getQuoteBtn to get a new quote
$('#getQuoteBtn').on('click', function() {
newQuote = randQuote;
// Get a different quote
while (newQuote == randQuote) {
newQuote = Math.floor(Math.random() * myObj.length);
}
randQuote = newQuote;
// Assign quote to element with id of quote
$('#quote').text(myObj[randQuote].Quote);
// Assign author to element with id of author
$('#author').text(' - ' + myObj[randQuote].Author);
// Remove spaces and special chars from author name for hashtag in tweet
var author = myObj[randQuote].Author.replace(/[^a-z0-9\s]/gi, '').replace(/[_\s]/g, '');
// Create tweet link for element with id of tweetThis
$('#tweetThis').attr('href', 'https://twitter.com/intent/tweet?text='
+ encodeURIComponent(myObj[randQuote].Quote.trim()) + '&hashtags=quotes,' + author);
});
});
function getQuote() {
// Get quotes from JSON
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
myObj = JSON.parse(this.responseText);
// Get a random quote
randQuote = Math.floor(Math.random() * myObj.length);
// Assign quote to element with id of quote
$('#quote').text(myObj[randQuote].Quote);
// Assign author to element with id of author
$('#author').text(' - ' + myObj[randQuote].Author);
// Remove spaces and special chars from author name for hashtag in tweet
var author = myObj[randQuote].Author.replace(/[^a-z0-9\s]/gi, '').replace(/[_\s]/g, '');
// Create tweet link for element with id of tweetThis
$('#tweetThis').attr('href', 'https://twitter.com/intent/tweet?text='
+ encodeURIComponent(myObj[randQuote].Quote.trim()) + '&hashtags=quotes,' + author);
}
};
// Get quotes from JSON file (change path to reflect your JSON)
// JSON should have keys of "Quote" and "Author"
xmlhttp.open("GET", "js/quotes.json", true);
xmlhttp.send();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment