Friday, August 3, 2007

Random Quotes with Javascript

[Note: This post has already inspired my next topic.... formatting code in blogger posts. This looks absolutely terrible. I apologize for any squinting-induced headaches]
Here's some javascript that I whipped up in order to teach myself some javascript fundamentals. My background is very OO and I had always thought javascript could not be object oriented. I was wrong!

function Quote( author, quote ) {
this.Author = author;
this.Quote = quote;
}

Quote.prototype.displayQuote = function() {
return '“'+ this.Quote+ '”';
}

Quote.prototype.displayAuthor = function() {
return this.Author == "" ? "" : " — "
+ this.Author.replace(/\s/g, " ");
}

Quote.prototype.toHTML = function() {
return this.displayQuote()+ this.displayAuthor();
}

Quote.prototype.render = function() {
document.write( this.toHTML() );
}

function Quotes() {
this.array = new Array();
}

Quotes.prototype.addQuote = function( q ) {
this.array[ this.array.length ] = q;
}

Quotes.prototype.add = function( author, quote ) {
this.addQuote( new Quote( author, quote ) );
}

Quotes.prototype.render = function ( index ) {
this.array[ index ].render();
}

Quotes.prototype.renderRandom = function () {
this.render( Math.floor( Math.random() * this.array.length ) );
}

var q = new Quotes();
q.add( "Pablo Picasso", "Bad artists copy. Great artists steal." );
q.add( "William Shakespeare", "The robb’d that smiles, steals something from the thief." );

//ADD OTHER FAVORITE QUOTES HERE

q.renderRandom();


So, what does it do? It creates a "class" (I may get jumped by the javascript nazis, but to this old school java--and more recently c#--programmer that's what it is) Quote that contains a quote and author, and has some simple display methods. Then a second class, Quotes, that just acts as a simple collection, with a randomizer function that spits out a ready to use quote for a web page. If you are reading this page on the scroungelounge blog, then you can see it in action at the bottom where my random quotes are displayed. Refresh the page if you don't believe me, it will (most likely) change!

For even better reuse, break out the "class" definitions to a separate file and use an include in the header:
<script type="text/javascript" src="quotes.js"></script>

Then just drop the quotes of your choice later on the page:

var q = new Quotes();
q.add( "Erik", "When you only add a single quotation here, the random results are pretty boring" );
q.renderRandom();


And there you have random quotes on your page in just a few lines of code. Now obviously there are probably easier, more straightforward ways of displaying a random quote, but my objective was to improve my javascript skills:

Skills["javascript"].IsImproved() == true
// mission accomplished!


If you want to see some great info on object oriented javascript (and get the technical scoop on from which this javascript hacking was based), read this article. Killer stuff Jonathan!