Skip to content

Instantly share code, notes, and snippets.

@apguan
Created June 7, 2016 10:17
Show Gist options
  • Save apguan/b2223089b39573d8762111909ded8cfb to your computer and use it in GitHub Desktop.
Save apguan/b2223089b39573d8762111909ded8cfb to your computer and use it in GitHub Desktop.
Wiki Random Quotes
<body>
<div class="container-fluid">
<div>
<title>Random Quotes</title>
<h2>A Little Bit of Interesting Every Day</h2>
</div>
<div id="background">
<h5 class="quote col-m-6" align="center" id="quote"><b>"</b>I never said it was easy. Giving up is easy<b>"</b></h5>
<br>
<br>
<p>-<span id="author">Maria V. Snyder</span></p>
<div id="button">
<button class="btn btn-lg" id="newquote">New Quote</button>
</div>
<div id="button">
</div>
<br>
</div>
<br>
<p id="sig" > <a href="http://codepen.io/apinguan/" id="sig" target="_blank">by Allen Guan</a></p>
</div>
</body>
$(document).ready(function() {
var quote = "I never said it was easy. Giving up is easy";
var author = "Maria V. Snyder";
function quoteReady(newQuote) {
quote = newQuote.quote.replace(/<(?:.|\n)*?>/gm, '');
author = newQuote.titles.replace(/<(?:.|\n)*?>/gm, '');
if (quote && author) {
$('#quote').replaceWith('<h5 class="quote col-m-6" align="center" id="quote"><b>"</b>' + quote + '<b>"</b></h5>');
$('#author').replaceWith('<span id="author">' + author + "</span>");
}
}
$("#newquote").click(function() {
WikiquoteApi.queryRandomTitle(function(title) {
WikiquoteApi.getRandomQuote(title, function(newQuote) {
quoteReady(newQuote);
});
});
});
});
//
// WikiquoteApi thanks to Nate Tyler. https://github.com/natetyler/wikiquotes-api
//
var WikiquoteApi = (function() {
var wqa = {};
var API_URL = "https://en.wikiquote.org/w/api.php";
/**
* Query based on "titles" parameter and return page id.
* If multiple page ids are returned, choose the first one.
* Query includes "redirects" option to automatically traverse redirects.
* All words will be capitalized as this generally yields more consistent results.
*/
wqa.queryTitles = function(titles, success, error) {
$.ajax({
url: API_URL,
dataType: "jsonp",
data: {
format: "json",
action: "query",
redirects: "",
titles: titles
},
success: function(result, status) {
var pages = result.query.pages;
var pageId = -1;
for (var p in pages) {
var page = pages[p];
// api can return invalid recrods, these are marked as "missing"
if (!("missing" in page)) {
pageId = page.pageid;
break;
}
}
if (pageId > 0) {
success(pageId);
} else {
error("No results");
}
},
error: function(xhr, result, status) {
error("Error processing your query");
}
});
};
wqa.queryRandomTitle = function(success, error) {
$.ajax({
url: API_URL,
dataType: "jsonp",
data: {
format: "json",
action: "query",
redirects: "",
list: "random",
rnnamespace: "0"
},
success: function(result, status) {
var title = result.query.random[0].title;
if (title !== undefined) {
success(title);
} else {
error("No results");
}
},
error: function(xhr, result, status) {
error("Error processing your query");
}
});
};
/**
* Get the sections for a given page.
* This makes parsing for quotes more manageable.
* Returns an array of all "1.x" sections as these usually contain the quotes.
* If no 1.x sections exists, returns section 1. Returns the titles that were used
* in case there is a redirect.
*/
wqa.getSectionsForPage = function(pageId, success, error) {
$.ajax({
url: API_URL,
dataType: "jsonp",
data: {
format: "json",
action: "parse",
prop: "sections",
pageid: pageId
},
success: function(result, status) {
var sectionArray = [];
var sections = result.parse.sections;
for (var s in sections) {
var splitNum = sections[s].number.split('.');
if (splitNum.length > 1 && splitNum[0] === "1") {
sectionArray.push(sections[s].index);
}
}
// Use section 1 if there are no "1.x" sections
if (sectionArray.length === 0) {
sectionArray.push("1");
}
success({
titles: result.parse.title,
sections: sectionArray
});
},
error: function(xhr, result, status) {
error("Error getting sections");
}
});
};
/**
* Get all quotes for a given section. Most sections will be of the format:
* <h3> title </h3>
* <ul>
* <li>
* Quote text
* <ul>
* <li> additional info on the quote </li>
* </ul>
* </li>
* <ul>
* <ul> next quote etc... </ul>
*
* The quote may or may not contain sections inside <b /> tags.
*
* For quotes with bold sections, only the bold part is returned for brevity
* (usually the bold part is more well known).
* Otherwise the entire text is returned. Returns the titles that were used
* in case there is a redirect.
*/
wqa.getQuotesForSection = function(pageId, sectionIndex, success, error) {
$.ajax({
url: API_URL,
dataType: "jsonp",
data: {
format: "json",
action: "parse",
noimages: "",
pageid: pageId,
section: sectionIndex
},
success: function(result, status) {
var quotes = result.parse.text["*"];
var quoteArray = [];
// Find top level <li> only
var $lis = $(quotes).find('li:not(li li)');
$lis.each(function() {
// Remove all children that aren't <b>
$(this).children().remove(':not(b)');
var $bolds = $(this).find('b');
// If the section has bold text, use it. Otherwise pull the plain text.
if ($bolds.length > 0) {
quoteArray.push($bolds.html());
} else {
quoteArray.push($(this).html());
}
});
success({
titles: result.parse.title,
quotes: quoteArray
});
},
error: function(xhr, result, status) {
error("Error getting quotes");
}
});
};
/**
* Search using opensearch api. Returns an array of search results.
*/
wqa.openSearch = function(titles, success, error) {
$.ajax({
url: API_URL,
dataType: "jsonp",
data: {
format: "json",
action: "opensearch",
namespace: 0,
suggest: "",
search: titles
},
success: function(result, status) {
success(result[1]);
},
error: function(xhr, result, status) {
error("Error with opensearch for " + titles);
}
});
};
/**
* Get a random quote for the given title search.
* This function searches for a page id for the given title, chooses a random
* section from the list of sections for the page, and then chooses a random
* quote from that section. Returns the titles that were used in case there
* is a redirect.
*/
wqa.getRandomQuote = function(titles, success, error) {
var errorFunction = function(msg) {
error(msg);
};
var chooseQuote = function(quotes) {
var randomNum = Math.floor(Math.random() * quotes.quotes.length);
success({
titles: quotes.titles,
quote: quotes.quotes[randomNum]
}
//console.log("Author: " +quotes.titles + " Quote: " + quotes.quotes[randomNum])
);
};
var getQuotes = function(pageId, sections) {
var randomNum = Math.floor(Math.random() * sections.sections.length);
wqa.getQuotesForSection(pageId, sections.sections[randomNum], chooseQuote, errorFunction);
};
var getSections = function(pageId) {
wqa.getSectionsForPage(pageId, function(sections) {
getQuotes(pageId, sections);
}, errorFunction);
};
wqa.queryTitles(titles, getSections, errorFunction);
};
wqa.getCompletelyRandomQuote = function(success, error) {
wqa.queryRandomTitle(function(title) {
wqa.getRandomQuote(title, success, error);
}, error);
};
/**
* Capitalize the first letter of each word
*/
wqa.capitalizeString = function(input) {
var inputArray = input.split(' ');
var output = [];
for (s in inputArray) {
output.push(inputArray[s].charAt(0).toUpperCase() + inputArray[s].slice(1));
}
return output.join(' ');
};
return wqa;
}());
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>
body {
font-family: 'Oswald', sans-serif;
background-color: #FAEBD7;
}
h2 {
margin-top: 50px;
margin-bottom: 50px;
text-align: center;
font-size: 50px;
}
.btn-lg {
border-radius: 0 !important;
width: 120px;
height: auto;
margin-bottom: 5px;
}
.btn:focus {
outline: none;
}
#background{
background-color: #000059;
width: 60%;
height: auto;
margin: 0 auto;
box-shadow: 4px 7px 15px 0px gray;
}
.quote{
width: 60%;
margin: 0px auto;
color: white;
font-size: 25px;
padding-top: 50px;
}
p {
color: white;
display: block;
text-align: center;
padding-bottom: 50px;
padding-right: 20px;
font-size: 15px;
}
#button {
width: 5%;
height: auto;
display: table;
margin: 0 auto;
}
#sig {
color: black;
font-family: 'Source Sans Pro', sans-serif;
font-size: 15px;
transition: color .3s;
}
#sig:hover {
color: #8B0000;
text-decoration: none;
}
#sig:active {
text-decoration: none;
}
a {
text-decoration: none;
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" />
<link href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/3.5.1/animate.min.css" rel="stylesheet" />

Wiki Random Quotes

This is my random quote generator. The API I'm using is one that pulls data from Wikipedia and displays it in the box.

A Pen by Allen Guan on CodePen.

License.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment