The Library
by Ryan Morris
HTML
<div id="books">
<form id="search-form" method="post" action="#">
<input type="text" name="query" placeholder="Search by title...">
<input type="submit" value="Search">
<input type="button" value="Refresh" id="refresh">
<label for="ajax">
<input type="checkbox" id="ajax" value="ajax" checked>
Ajax
</label>
</form>
<a id="add-btn" href="#">Add a new book</a>
<form id="add-form" method="post" action="#">
<input type="text" name="title" placeholder="Title">
<input type="text" name="author" placeholder="Author">
<input type="text" name="pages" placeholder="Pages">
<input type="submit" value="Add Book">
</form>
<table id="books-table">
<thead>
<tr>
<th>Title</th>
<th>Author</th>
<th>Pages</th>
<th>Current Page</th>
</tr>
</thead>
<tbody></tbody>
</table>
</div>
CSS
body {
font-family: Century Gothic, sans-serif;
font-size:67%;
}
form {
margin:0;
}
table {
border:1px dotted #ccc;
width:100%;
padding:0;
margin:0;
border-collapse:collapse;
}
table td {
padding:0;
margin:0;
}
thead {
background-color:#fafafa;
font-size:1em;
}
thead th {
padding:0;
margin:0;
text-align:left;
border-bottom:1px solid #000;
}
tbody tr:hover {
background-color:#f90;
cursor:pointer;
}
tbody tr.featured {
font-weight:bold;
}
#add-btn {
float:left;
padding:0;
margin:5px 0 10px 0;
}
#add-form {
display:none;
clear:both;
border:1px solid #ccc;
padding:5px;
margin:0 0 10px 20px;
background-color:#f9f9f9;
}
#add-form input {
display:block;
margin-bottom:5px;
}
JavaScript
// converts json object to url params var1=&var2=
// one level deep
var quickParamaterize = function (obj) {
var str = "";
for (var key in obj) {
if (str != "") {
str += "&";
}
str += key + "=" + obj[key];
}
return str;
}
// Fetch the initial data set
var fetchBooks = function (callback) {
var httpRequest = new XMLHttpRequest();
httpRequest.onreadystatechange = callback;
httpRequest.open('POST', '/echo/json/', true);
httpRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
httpRequest.send(quickParamaterize({
json: JSON.stringify({
success: true,
data: [{
id: 1,
title: "Cosmos",
author: "Carl Sagan",
pages: 300
}, {
id: 20,
title: "Winter's Tale",
author: "Mark Helprin",
pages: 500
}, {
id: 20,
title: "Jubal Sackett",
author: "Louis L'amour",
pages: 150,
featured: true
}]
}),
delay: 2
}));
};
var basicCallback = function () {
if (this.readyState === 4) {
// everything is good, the response is received
var response = JSON.parse(this.responseText);
if (
this.status === 200 && response.success && response.data) {
// foreach book
var tableBodyEL = document.querySelector("#books table tbody");
for (var i = 0; i < response.data.length; i++) {
console.log(response.data[i]);
// add a new row
var newTr = document.createElement("tr");
newTr.setAttribute("data-id", response.data[i].id);
if (
response.data[i].featured && response.data[i].featured === true) {
newTr.className =...