Random Bookshelf Generator
HTML
<button>REFRESH</button>
<div id="bookshelf"></div>
CSS
#bookshelf {
font-family: calibri;
list-style: none;
width: 400px;
border: 20px solid #ddd;
border-bottom: 0;
background: #eee;
}
.shelf {
display: block;
height:20px; width:100%;
margin-top: -4px;
background: #ddd;
white-space: nowrap;
overflow: hidden;
}
.book {
display: inline-block;
width:40px; height:100%;
margin-right: 4px;
background: tomato;
}
.book:first-child {
margin-left: 4px;
}
.book:last-child {
margin-right: 0;
}
JavaScript
function addShelf() {
$('#bookshelf').append('<div class="shelf"></div>');
}
function generateBooks(nb) {
var bShelf = $('#bookshelf');
var shelfW = bShelf.width();
var margin = 4;
var booksW = margin;
bShelf.empty();
for(var i=0; i<nb; i++) {
var b = randomBook();
var bWidth = b.width();
if(booksW + bWidth + margin >= shelfW) {
addShelf();
booksW = margin;
}
booksW += bWidth + margin;
bShelf.append(b);
}
addShelf();
}
function randomBook() {
var width = Math.floor(Math.random()*40) + 10;
var height = Math.floor(Math.random()*50) + 150;
var margin = 200 - height;
return $('<div class="book"></div>')
.css('width', width+'px')
.css('height', height+'px')
.css('margin-top', margin+'px');
}
generateBooks(20);
$('button').click(function() { generateBooks(20); });