<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>O! Mr Speaker! &#187; jQuery</title>
	<atom:link href="http://www.mrspeaker.net/category/nerd/jquery/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.mrspeaker.net</link>
	<description>Javascript flâneur, internet flibbertygibbert</description>
	<lastBuildDate>Thu, 02 Feb 2012 13:18:44 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.2.1</generator>
		<item>
		<title>Reducing map: jQuery vs jQuery vs JavaScript</title>
		<link>http://www.mrspeaker.net/2011/04/27/reducing-map/</link>
		<comments>http://www.mrspeaker.net/2011/04/27/reducing-map/#comments</comments>
		<pubDate>Wed, 27 Apr 2011 12:01:06 +0000</pubDate>
		<dc:creator>Mr Speaker</dc:creator>
				<category><![CDATA[jQuery]]></category>

		<guid isPermaLink="false">http://www.mrspeaker.net/?p=2573</guid>
		<description><![CDATA[The map/reduce (and their friends filter, each, flatten etc) paradigm provides a general way to manipulate lists and streams. This is particularly well suited to web work - where we spend most of our days playing with lists of DOM elements. Recent versions of JavaScript give us the tools to do this work natively but [...]]]></description>
			<content:encoded><![CDATA[<p>The map/reduce (and their friends filter, each, flatten etc) paradigm provides a general way to manipulate lists and streams. This is particularly well suited to web work - where we spend most of our days playing with lists of DOM elements. Recent versions of JavaScript give us the tools to do this work natively but before that we had to roll our own, or use a library. jQuery has had some similar features since way-back-when, so today we're going to do a bit of "compare &amp; contrast" on the <em>map</em> function: jQuery vs jQuery vs JavaScript!</p>
<p><em>Map</em> iterates over a collections and applies a function to each element - returning a new, usually modified, list. Our tests will examine jQuery's <a href="http://api.jquery.com/map/">"inline" map</a> with it's <a href="http://api.jquery.com/jQuery.map/">global $.map</a> map, and <a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/map">JavaScript's native map</a> function. The object (no pun intended) is to see how each implementation varies in terms of the parameters and the value of <em>this</em> we get each iteration, and how they handle weird arrays. </p>
<p><span id="more-2573"></span>Our initial task will to be to turn a list of &lt;li&gt; tags into an array of numerical values that each element contains. The input will therefore be:</p>
<pre><code>&lt;ul id="list"&gt;
  &lt;li&gt;1&lt;/li&gt;
  &lt;li&gt;2&lt;/li&gt;
  &lt;li&gt;3&lt;/li&gt;
&lt;/ul&gt;</pre>
<p></code></p>
<p>And the required output is a simple JavaScript array:</p>
<pre><code>[1, 2, 3]</code></pre>
<p>jQuery likes to keep things jQuery-y, so some of the outputs (and inputs) will be wrapped in the jQuery function (i.e. <code>jQuery(1, 2, 3)</code> instead of <code>[1, 2, 3]</code>). Chrome's logger will show both the values as <code>[1, 2, 3]</code> - but if you tried to <code>.reverse</code> a jQuery object it's going to die - so if you need to get at the underlying array from a jQuery object then used the <code>.get</code> method: <code>jQuery(1, 2, 3).get()</code>.</p>
<p class="note"><a href="https://gist.github.com/944209">The code for the tests</a> is up on GitHub. I've abstracted the tests a bit for code readability, but I'll list the "long version" here so it makes more sense out of context. Each method will print the collection ("Input"), the <em>this</em> value and arguments ("args") for each item iteration, and the result ("Output").</p>
<p>Ok, let's run some tests...</p>
<h3 style="padding-top:20px">Ex 1a: inline jQuery map</h3>
<pre><code>$("#list li").map(function(){
  return parseInt($(this).text(), 10);
});</code></pre>
<p class='o-out'><span class='o-before'>Input:</span> jQuery(li, li, li)<br />
<span class='o-this'>this:</span> &lt;li&gt; <span class='o-this'>args:</span> [0, li]<br />
<span class='o-this'>this:</span> &lt;li&gt; <span class='o-this'>args:</span> [1, li]<br />
<span class='o-this'>this:</span> &lt;li&gt; <span class='o-this'>args:</span> [2, li]<br />
<span class='o-after'>Output:</span> jQuery(1, 2, 3)</p>
<h3 style="padding-top:20px">Ex 1b: global jQuery map</h3>
<pre><code>$.map($("#list li"), function(el){
  return parseInt($(el).text(), 10);
});</code></pre>
<p class='o-out'><span class='o-before'>Input</span>: jQuery(li, li, li)<br />
<span class='o-this'>this</span>: DOMWindow <span class='o-this'>args:</span> [li, 0, undefined]<br />
<span class='o-this'>this</span>: DOMWindow <span class='o-this'>args:</span> [li, 1, undefined]<br />
<span class='o-this'>this</span>: DOMWindow <span class='o-this'>args:</span> [li, 2, undefined]<br />
<span class='o-after'>Output</span>: [1, 2, 3]</p>
<p>There are some notable differences between the two jQuery methods. The inline version scopes to the list, so <em>this</em> is the element, and the first argument to the callback is the element's index. The second is the same as <em>this</em> (for some reason).</p>
<p>The global version scopes to the document window. To get the element you need to look at the first parameter. The index is the second, and we get a handy undocumented reference to <em>undefined</em> as the third. (I really should have a squizz at the jQuery source code to see what is going on here). The global map also returns us a real JavaScript array - not a jQuery array-like array.</p>
<h3 style="padding-top:20px">Ex 1c: JavaScript map over array</h3>
<pre><code>$("#list li").get().map(function(el){
  return parseInt($(el).text(), 10);
});</code></pre>
<p class='o-out'><span class='o-before'>Input:</span> [li, li, li]<br />
<span class='o-this'>this:</span> DOMWindow <span class='o-this'>args:</span> [li, 0, [li, li, li]]<br />
<span class='o-this'>this:</span> DOMWindow <span class='o-this'>args:</span> [li, 1, [li, li, li]]<br />
<span class='o-this'>this:</span> DOMWindow <span class='o-this'>args:</span> [li, 2, [li, li, li]]<br />
<span class='o-after'>Output:</span> [1, 2, 3]</p>
<p>The native JavaScript map gives us an output that looks like the global jQuery map - except we get something a bit more useful as the third parameter: the original collection. The original collection in this case is the .get() value of the jQuery selection - that is, a real array. But it works over a jQuery collection too, if we apply it - as in the following example...</p>
<h3 style="padding-top:20px">Ex 1d: JavaScript map over jQuery collection</h3>
<pre><code>Array.prototype.map.call($("#list li"), function(el){
    return parseInt($(el).text(), 10);
});</code></pre>
<p class='o-out'><span class='o-before'>Input:</span> jQuery(li, li, li)<br />
<span class='o-this'>this:</span> DOMWindow <span class='o-this'>args:</span> [li, 0, jQuery(li, li, li)]<br />
<span class='o-this'>this:</span> DOMWindow <span class='o-this'>args:</span> [li, 1, jQuery(li, li, li)]<br />
<span class='o-this'>this:</span> DOMWindow <span class='o-this'>args:</span> [li, 2, jQuery(li, li, li)]<br />
<span class='o-after'>Output:</span> [1, 2, 3]</p>
<p>That was just to show the output was the same with the jQuery input. The native map also lets you specify an optional parameter after the callback function to scope the map too - rather than the DOMWindow object.</p>
<p>There are a few things in common with each implementation: they all have a way to access the element and the element's index (zero offset), and none of them mutate the original collection. It's not hard to figure out the differences and adapt your style - but it's not all rosy once we leave the land of jQuery...</p>
<h2>Holey arrays, batman</h2>
<p>All three map implementations work over regular ol' arrays. However, regular ol' arrays in JavaScript have a tendency to not be that regular at all: we can have null values, and "holes" that can trip up our brave iterators.</p>
<pre><code>var holey = [ "1", "2", null, ["4a", "4b"], , "6"];</code></pre>
<p class='o-out'><span class='o-after'>Output:</span> ["1", "2", null, Array[2], undefined, "6"]</p>
<p>Here we have an array that is pretty funky. It's got strings, and nulls, and arrays, and holes. First we'll look at how our maps index such a quirky beast:</p>
<h3>Ex 2a: jQuery global map-to-index</h3>
<pre><code>$.map(holey, function(el, index){
    return index;
});</code></pre>
<p class='o-out'><span class='o-after'>Output:</span> [0, 1, 2, 3, 4, 5]</p>
<h3>Ex 2b: JavaScript map-to-index</h3>
<pre><code>holey.map(function(el, index){
    return index;
});</code></pre>
<p class='o-out'><span class='o-after'>Output:</span> [0, 1, 2, 3, undefined, 5]</p>
<p>Oh kay... be careful there - our "hole" is not processed by the native map, so we get no value for index, which results in a big fat <em>undefined</em> in the middle. Best keep that in mind.</p>
<p>Finally, we'll look at what happens if we map the elements to themselves.</p>
<h3>Ex 2c: JavaScript map-to-element</h3>
<pre><code>holey.map(function(el){
    return el;
});</code></pre>
<p class='o-out'><span class='o-after'>Output:</span> ["1", "2", null, ["4a", "4b"], undefined, "6"]</p>
<h3>Ex 2d: jQuery global map-to-element</h3>
<pre><code>$.map(holey, function(el){
    return el;
});</code></pre>
<p class='o-out'><span class='o-after'>Output:</span> ["1", "2", "4a", "4b", "6"]</p>
<p>Errrgh... Um, wow? Native JavaScript acts as (I) expected, but there's something peculiar happening in the world of jQuery. Actually, if you consult the docs then you'll see it's not a flaw but a feature. Null values are dropped from the resulting map, and any arrays are flattened one level (if fact, if you need to combat that you can return the element wrapped in an extra array).</p>
<p>That's a wacky feature - map is actually a flatmap and filter type thing in jQuery. So make sure you know what you're doing before you go playing with JavaScript arrays with them!</p>
<p>Ok. That'll do us for now. Things get even more funky if you delete items during a loop, but if you're doing that then you're on your own. In the next post we'll have a look at <a href="http://www.mrspeaker.net/2011/05/02/conventional-interfaces/">some map/reduce/filter/etc methods in action</a>, and we'll see why it's important to have dissected poor old map. See you then.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.mrspeaker.net/2011/04/27/reducing-map/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>Long jQuery fades eats CPU</title>
		<link>http://www.mrspeaker.net/2011/03/22/long-jquery-fades-eats-cpu/</link>
		<comments>http://www.mrspeaker.net/2011/03/22/long-jquery-fades-eats-cpu/#comments</comments>
		<pubDate>Mon, 21 Mar 2011 14:02:21 +0000</pubDate>
		<dc:creator>Mr Speaker</dc:creator>
				<category><![CDATA[jQuery]]></category>

		<guid isPermaLink="false">http://www.mrspeaker.net/?p=2305</guid>
		<description><![CDATA[While doing a little refreshing around these parts I noticed that the "fading bubbles" that I have were chewing up a ridiculous amount of CPU when the page loaded. I had 15 or so bubbles rigged to fade in verrrrrry slowly - over 20 seconds - after window.onload fired. I thought I must have had [...]]]></description>
			<content:encoded><![CDATA[<p>While doing a little refreshing around these parts I noticed that the "fading bubbles" that I have were chewing up a <em>ridiculous</em> amount of CPU when the page loaded. I had 15 or so bubbles rigged to fade in verrrrrry slowly - over 20 seconds - after window.onload fired. I thought I must have had some crazy infinite loop or some such, but no... after whittling things down I ended up creating this test page:</p>
<p><a href="http://mrspeaker.net/dev/jqlongfade/">jQuery long fade test</a></p>
<p>If you open up Activity Monitor and click the "big fade" button, the screen will slowly fade in (to background colour #bada55, naturally) and your CPU will say bye-bye. Similarly, if you fade in a bunch of items over a long time you'll see a pretty serious drain too.</p>
<p>I haven't gone looking over on the mailing lists to see if this is a "known issue", or started digging into the source, 'cause I'm a lil' pressed for time at the moment - but if you found this page while googlin' to fix your fading woes, I feel your pain and will tell you to do what I shoulda done: use CSS transitions!</p>
<p>Finally, while checking I used the correct spelling of "whittling" I found this statement on <a href="http://www.whittling.com/">the official whittling website</a>:<br />
<blockquote>Welcome to the world of whittling, a hobby for some, an obsession for others, a joy for all.</p></blockquote>
<p>I'm a fan of whittling and all, but that just seems like a logical fallacy to me.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.mrspeaker.net/2011/03/22/long-jquery-fades-eats-cpu/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Two teams, one cup</title>
		<link>http://www.mrspeaker.net/2010/07/11/the-world-cup-final/</link>
		<comments>http://www.mrspeaker.net/2010/07/11/the-world-cup-final/#comments</comments>
		<pubDate>Sun, 11 Jul 2010 09:35:21 +0000</pubDate>
		<dc:creator>Mr Speaker</dc:creator>
				<category><![CDATA[jQuery]]></category>
		<category><![CDATA[Wide world]]></category>

		<guid isPermaLink="false">http://www.mrspeaker.net/?p=1662</guid>
		<description><![CDATA[It's been a grueling battle, but unsurprisingly jQuery Novice to Ninja has made the World Cup Final. Tonight's game is not going to be easy - up against the formidable Kevin Yank/Cameron Adams combination who, as always, are in excellent form. But if you're the betting type, I'd be putting my dollar on a free [...]]]></description>
			<content:encoded><![CDATA[<p><img src="http://www.mrspeaker.net/images/sitepoint.png" alt="Sitepoint World Cup" title="Sitepoint World Cup" width="444" height="339" class="" /><br />
It's been a grueling battle, but unsurprisingly <em>jQuery Novice to Ninja</em> has made the <a href="http://sale.sitepoint.com/">World Cup Final</a>. Tonight's game is not going to be easy - up against the formidable <a href="http://www.sitepoint.com/books/javascript1/">Kevin Yank/Cameron Adams combination</a> who, as always, are in excellent form.</p>
<p><span id="more-1662"></span>But if you're the betting type, I'd be putting my dollar on a free jQuery book - because if the <a href="http://search.sitepoint.com/?q=simply+javascript">SitePoint search results</a> are anything to go by, we've got it in the bag...<br />
<img src="http://www.mrspeaker.net/images/simplyjquery.png" alt="Simply jQuery" title="Simply jQuery" width="450" height="160" class="frame-left" /></p>
]]></content:encoded>
			<wfw:commentRss>http://www.mrspeaker.net/2010/07/11/the-world-cup-final/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Book review: &#8220;jQuery: Novice to Ninja&#8221;</title>
		<link>http://www.mrspeaker.net/2010/02/24/novice-to-ninja/</link>
		<comments>http://www.mrspeaker.net/2010/02/24/novice-to-ninja/#comments</comments>
		<pubDate>Wed, 24 Feb 2010 06:52:24 +0000</pubDate>
		<dc:creator>Mr Speaker</dc:creator>
				<category><![CDATA[jQuery]]></category>
		<category><![CDATA[Wide world]]></category>

		<guid isPermaLink="false">http://www.mrspeaker.net/?p=1536</guid>
		<description><![CDATA[I just finished reading "jQuery: Novice to Ninja" by Earle Castledine &#038; Craig Sharkie, and I have to say - it was as delightful as it was disturbing: without a doubt it is this year's must-read sleeper hit. The authors excel in propelling the reader on an epic personal journey that immerses them in the [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://www.sitepoint.com/books/jquery1/" title="jQuery: Novice to Ninja"><img src="http://www.mrspeaker.net/images/cover-jquery1.png" alt="jQuery: Novice to Ninja" title="cover-jquery1" width="138"  style="float:right" /></a>I just finished reading "<a href="http://www.sitepoint.com/books/jquery1/" title="jQuery: Novice to Ninja">jQuery: Novice to Ninja</a>" by Earle Castledine &#038; Craig Sharkie, and I have to say - it was as delightful as it was disturbing: without a doubt it is this year's must-read sleeper hit. The authors excel in propelling the reader on an epic personal journey that immerses them in the sights, sounds, and smells of jQuery 1.4. Long after the last page has been turned, and the powerful electric sparks of wonder subside... a feeling of gentle tranquility and wisdom remain. And we get $2 a copy.</p>
<p><span id="more-1536"></span>The book opens with what we might assume to be the present day. A sense of tension and foreboding seeps from the text as we are introduced to the perils and dangers of cross-browser Web development. A likeable and handsome protagonist - the reader - emerges from darkness and attempts to harness the powers of jQuery to overcome these obstacles. By the end of the piece, our hero has changed: the naivety and timidness replaced with a quiet strength - an enchanting energy that knows no boundaries.</p>
<p>At least, that's what I got out of it. If you wanted to ignore the sub-text then I guess you'd just say it was a kick-ass jQuery book. </p>
<p>I'll conclude this review by saying that it is possibly the most important work released in the last 500 years, and leave you with an appropriate quote from Australian television personality, John Safran:<br />
<blockquote>If you're not writing your own reviews, then you don't deserve to be famous.</p></blockquote>
]]></content:encoded>
			<wfw:commentRss>http://www.mrspeaker.net/2010/02/24/novice-to-ninja/feed/</wfw:commentRss>
		<slash:comments>10</slash:comments>
		</item>
		<item>
		<title>DIY Old-school racing game: Part 1</title>
		<link>http://www.mrspeaker.net/2010/02/18/racing-game-with-jquery/</link>
		<comments>http://www.mrspeaker.net/2010/02/18/racing-game-with-jquery/#comments</comments>
		<pubDate>Thu, 18 Feb 2010 00:13:03 +0000</pubDate>
		<dc:creator>Mr Speaker</dc:creator>
				<category><![CDATA[Javascript]]></category>
		<category><![CDATA[jQuery]]></category>

		<guid isPermaLink="false">http://www.mrspeaker.net/?p=1458</guid>
		<description><![CDATA[Remember Pole Position? Outrun? PowerDrift? Lotus Esprit Turbo Challenge? Yeah you do! Remember jQuery 1.4? Most likely! Let's combine those two memories into one DIY project and make our very own old-school racing game with jQuery 1.4, shall we? To prove it could work, here's an early proof-of-concept to hopefully pique your interest. It'll take [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://www.mrspeaker.net/dev/racer/" alt="8bit racing game"><img src="http://www.mrspeaker.net/images/racer-1.png" alt="old school racer" title="old school racer" width="150" height="103" class="frame-right" /></a>Remember Pole Position? Outrun? PowerDrift? Lotus Esprit Turbo Challenge? Yeah you do! Remember jQuery 1.4? Most likely! Let's combine those two memories into one DIY project and make our very own old-school racing game with jQuery 1.4, shall we?</p>
<p>To prove it could work, here's an early <a href="http://www.mrspeaker.net/dev/racer/">proof-of-concept</a> to hopefully pique your interest. It'll take us a few posts to get there - but that was just something I cobbled together (and the perspective is messed up)... it will be even cooler when we arrive!</p>
<p><span id="more-1458"></span>Now, I know at this point you're probably pretty excited - but I should warn you up front, I have a poor track record of following through on promises of "multi-part" tutorials. To this day I still receive threatening, tearful emails wondering when "part 3" of my <a href="http://www.mrspeaker.net/2009/08/01/3d-html5-part-0/">3d with HTML5</a> will be complete. But I can promise you this: we may not end up with a game, but we WILL end up with at least a cool curvey racetrack with some cars on it. Even if it runs at 2 frames a second.</p>
<p>Anyhoo, let's get on with it. In this first part we'll get everything set up and our screen-drawing animation technique in place. In the next part we'll add racing stripes: and then things get awesome. </p>
<p>But first of all, a back-story. Over the course of my illustrious JavaScript tinkering days I've implemented countful "classics": Pong, shoot'em ups, platformers, Tetris... all the basics. When deciding on what to waste my time on next I started wondering about the ol' racing games of the past and how they worked. I spent a fair chunk of time trying to figure it out in my head... line drawing and curve algorithms and so forth. But I concluded that there must be some trick - no way could the C64 redraw a full bitmap screen so fast?! How could it be done?! It started to hurt my brain, and I was all set to give up... when out-of-the-blue a friend emailed me this <a href="http://www.gorenfeld.net/lou/pseudo/">tome of enlightenment</a>.</p>
<p>Everything you've ever wanted to know about old racing games but were too stupid to figure out on your own! And of course, behind the technique is a genius-ly simple trick: take a flat image of a "perspective-style" road trailing off into the distance. Break the road into the individual lines that make up the image, then move those lines left or right as required to create the illusion of a curving road! Now, after pouring over <em>Lou's Pseudo 3d Page v0.9</em> I've managed to get a racer-style road working (and looking very cool)... but I have probably misunderstood some of the finer points of his writings - so this might not be the nicest way to do it. But it's a start, hey!</p>
<p>The first thing that isn't really mentioned in the article, but I think needs to be done is to make the road image quite a bit wider than the view port - so that when the road "curves" sharply, and you position the line's X position waaaay out to one side, the line doesn't stop in the middle of the screen - thus revealing the whole trick. Click on the image below to see the road graphic we'll be using. There are two "roads" which we'll intersperse to create the stripey-road effect.</p>
<p><a href="/dev/racer/road.png"><img src="/dev/racer/road.png" width="450" /></a></p>
<p>I've joined the two road graphics together so we can manipulate it as a CSS sprite. As you'd expect, HTML and CSS don't really give us a nice way to manipulate the lines of an image individually. We're going to need to do some trickery: add a couple of hundred 1 pixel-high div elements to the page, and assign them all the same background image. Then we'll offset the background image position to show the correct line for that part of the road! Dodgy, but cool!</p>
<p>Right, some code... Here's some "base" HTML for those following along at home: <a href="/dev/racer/racer0.html">Racer v0.0.0.0</a>, but there's nothing special in it - feel free to start your own.</p>

<div class="wp_syntax"><div class="code"><pre class="css" style="font-family:monospace;"><span style="color: #cc00cc;">#board</span><span style="color: #00AA00;">&#123;</span>
	<span style="color: #000000; font-weight: bold;">width</span><span style="color: #00AA00;">:</span><span style="color: #933;">320px</span><span style="color: #00AA00;">;</span>
	<span style="color: #000000; font-weight: bold;">background-color</span><span style="color: #00AA00;">:</span><span style="color: #cc00cc;">#008ace</span><span style="color: #00AA00;">;</span>
<span style="color: #00AA00;">&#125;</span>
.line<span style="color: #00AA00;">&#123;</span>
	<span style="color: #000000; font-weight: bold;">width</span><span style="color: #00AA00;">:</span> <span style="color: #933;">320px</span><span style="color: #00AA00;">;</span>
	<span style="color: #000000; font-weight: bold;">height</span><span style="color: #00AA00;">:</span> <span style="color: #933;">1px</span><span style="color: #00AA00;">;</span>
	<span style="color: #000000; font-weight: bold;">overflow</span><span style="color: #00AA00;">:</span> <span style="color: #993333;">hidden</span><span style="color: #00AA00;">;</span>
	<span style="color: #000000; font-weight: bold;">background</span><span style="color: #00AA00;">:</span><span style="color: #993333;">transparent</span> <span style="color: #993333;">url</span><span style="color: #00AA00;">&#40;</span><span style="color: #ff0000; font-style: italic;">road.png</span><span style="color: #00AA00;">&#41;</span> <span style="color: #993333;">no-repeat</span> <span style="color: #cc66cc;">0</span> <span style="color: #cc66cc;">0</span><span style="color: #00AA00;">;</span>
<span style="color: #00AA00;">&#125;</span></pre></div></div>

<p>The "board" will be our main screen div element, and the <code>line</code> class will be the individual lines of the screen. You'll need to grab a copy of the <code>road.png</code> file from above. Next, we'll set up our object literal to hold all the game details in. This is our game "controller" and ensures we play nicely with any other JavaScript on the page.</p>

<div class="wp_syntax"><div class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #003366; font-weight: bold;">var</span> tracks <span style="color: #339933;">=</span> <span style="color: #009900;">&#123;</span>
	num_strips<span style="color: #339933;">:</span> <span style="color: #CC0000;">220</span><span style="color: #339933;">,</span>
	half_num_strips<span style="color: #339933;">:</span> <span style="color: #CC0000;">110</span><span style="color: #339933;">,</span>
	strips <span style="color: #339933;">:</span> <span style="color: #009900;">&#91;</span><span style="color: #009900;">&#93;</span><span style="color: #339933;">,</span>
	init <span style="color: #339933;">:</span> <span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
		<span style="color: #006600; font-style: italic;">// Set up the screen, then...	</span>
		<span style="color: #006600; font-style: italic;">// Start the animation running	</span>
		setInterval<span style="color: #009900;">&#40;</span> <span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span> tracks.<span style="color: #660066;">update</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#125;</span><span style="color: #339933;">,</span> <span style="color: #CC0000;">200</span> <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span><span style="color: #339933;">,</span>
	update <span style="color: #339933;">:</span> <span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
		<span style="color: #006600; font-style: italic;">// Update the screen</span>
	<span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span><span style="color: #339933;">;</span></pre></div></div>

<p>We aren't doing anything yet - just setting everything up. Our <code>tracks</code> object will be responsible for setting up the screen, and then updating it every 200 milliseconds. We've also defined a few properties at the top: <code>num_strips</code>, <code>half_num_strips</code>, and <code>strips</code>. The <code>strips</code> array will hold a reference to each of the 1 pixel-high lines of the screen. The <code>num_strips</code> property defines how many pixels high the entire screen will be, and the <code>half_num_strips</code> is just half that: it saves us having to calculate <code>num_strips / 2</code> all over the place (which is important in some of our loops!).</p>
<p>Right, let's draw the initial screen then shall we? Inside the <code>init</code> function, we want to make a loop that appends as many 1 pixel-high div elements that fit on our screen, and keep a reference to them for later.</p>
<pre><code>// Draw the screen lines
for( i = 0; i < this.num_strips; i++ ){
	var strip = $( "&lt;div&gt;&lt;/div&gt;" ).addClass( "line" ).appendTo( "#board" );
	this.strips.push( strip );
}</code></pre>
<p>Now we have 220 div elements squished inside the <code>#board</code> container div! To see it in action, you'll need to fire the <code>tracks.init</code> function in your <code>document-ready</code> handler:</p>
<pre><code>$(document).ready(function(){
	tracks.init();
});</code></pre>
<p>If you inspect the <code>#board</code> element with Firebug you'll see that there are hundreds of divs - but why isn't the first line of the image appearing in each div? Well, because I made the first line of the image transparent, 'cause I'm too lazy to do things properly. As always when you're being too lazy, it comes back to bight us later. But if you change the "no-repeat 0 0" in the css declaration to "no-repeat 1 0" or something like that, then you should see the repeated line fill the screen.</p>
<p>Having the same line repeated is not what we want though - we want to draw the entire road on screen. We'll have to do some math. In Lou's article he describes everything happening upside down - you draw the screen from the bottom to the top. I decided to do this too... it's going to make things scary later on when we get to "hills", but too bad. In the <code>update</code> function (which is being called every 200 milliseconds) we will set each line to its correct position. We know that (for now) we only have to draw from the bottom of the screen to half way up the screen (where the horizon starts), so we'll only loop over these lines. Inside the loop we'll calculate how far we need to move the background image to draw the correct line.</p>
<pre><code>// Update the bottom half of the screen
for( var i = this.num_strips - 1; i >= this.half_num_strips; i-- ){
	var tex = 111;
	var y_off = ( i - ( this.half_num_strips ) ) + tex;

	this.strips[ i ].css( "background-position",  "-345px -" + y_off + "px"	);
}</code></pre>
<p>Inside the loop we figure out the Y position for each screen line. The <code>tex</code>  (for "texture") variable will be used later when it comes time to figure out how to draw the "racing stripes" on the road. The Y position offset is used to alter the background position of the image - so that the correct line is drawn in the correct place. The <code>tex</code> variable adds 111 pixels to the background image - that's why we see the bottom road. If you change it to 1, then you'll see it draws the top screen. Now, if you're feeling adventurous, change it to <code>var tex = Math.random() < 0.5 ? 1 : 111;</code> to get an idea about how the next tutorial will work!</p>
<p>The last thing we'll do is add a car, for good luck. It's just <a href="/dev/racer/car.png">an image I ripped out of Pole Position</a>. Looks lovely though. We'll define it with some CSS:</p>
<pre><code>.car{
	width:90px;
	height:33px;
	background:transparent url(car.png) no-repeat 0 0;
	position:absolute;
	top:190px;
	left:122px;
}</code></pre>
<p>And then in the <code>init</code> function (after the screen set up, and before the timer) we'll add it to the page with jQuery:
<pre><code>// Draw the car
var car = $( "&lt;div&gt;&lt;/div&gt;" ).addClass( "car" ).appendTo( "#board" );</code></pre>
<p>Have a look at <a href="http://www.mrspeaker.net/dev/racer/racer1a.html">what we've got so far</a>. Nothing spectacular - and hardly ANY jQuery... but the basics are in place and the scene is set. Have a play with all the variables and CSS properties we've set, and join me next time as we continue to push jQuery far in to the distant past!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.mrspeaker.net/2010/02/18/racing-game-with-jquery/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>.index() becomes cool in jQuery 1.4</title>
		<link>http://www.mrspeaker.net/2009/12/05/index-in-jquery/</link>
		<comments>http://www.mrspeaker.net/2009/12/05/index-in-jquery/#comments</comments>
		<pubDate>Sat, 05 Dec 2009 06:28:57 +0000</pubDate>
		<dc:creator>Mr Speaker</dc:creator>
				<category><![CDATA[jQuery]]></category>
		<category><![CDATA[Nerd]]></category>

		<guid isPermaLink="false">http://www.mrspeaker.net/?p=1411</guid>
		<description><![CDATA[With jQuery 1.4 just around the corner, it's time to start looking at what's new. One nice change is the updated functionality of the index method. Previously, well, it was a pain in the bum to get the index of an element in a selection - and required a pretty convoluted syntax. Now it's super [...]]]></description>
			<content:encoded><![CDATA[<p>With jQuery 1.4 just around the corner, it's time to start looking at what's new. One nice change is the updated functionality of the <code>index</code> method. Previously, well, it was a pain in the bum to get the index of an element in a selection - and required a pretty convoluted syntax. Now it's super easy... <code>$(this).index()</code>. Let's have a look at a 'lil example:</p>
<p><span id="more-1411"></span>Say we have an unordered list of items:
<pre><code>&lt;ul id="tags"&gt;
	&lt;li&gt;jQuery&lt;/li&gt;
	&lt;li&gt;Javascript&lt;/li&gt;
	&lt;li&gt;reference&lt;/li&gt;
	...
&lt;/ul&gt;</code></pre>
<p>The user can click on a list item to select it. When a click happens, we need to find out what the item's index is, relative to all its siblings....
<pre><code>$("#tags li").click(function(){
    alert( "Hi, I'm element " + $(this).index() );
});</code></pre>
<p>That's all there is to it. Super useful!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.mrspeaker.net/2009/12/05/index-in-jquery/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>The road to jQuery 1.4: at a glance</title>
		<link>http://www.mrspeaker.net/2009/11/20/the-road-to-jquery-1-4-at-a-glance/</link>
		<comments>http://www.mrspeaker.net/2009/11/20/the-road-to-jquery-1-4-at-a-glance/#comments</comments>
		<pubDate>Fri, 20 Nov 2009 09:13:13 +0000</pubDate>
		<dc:creator>Mr Speaker</dc:creator>
				<category><![CDATA[jQuery]]></category>

		<guid isPermaLink="false">http://www.mrspeaker.net/?p=1326</guid>
		<description><![CDATA[Ok, here's something you'll want to refer to daily... the current status of the jQuery 1.4 "TODO list", or as I like to call it, "Report 37". Usually when people on the jQuery dev lists ask "When will jQuery 1.4 be ready?" they are met with a resigned (resigned not resiged) answer: "When it's ready". [...]]]></description>
			<content:encoded><![CDATA[<div style='float:right;padding:10px 10px 10px 0'><object width="160" height="130"><param name="movie" value="http://www.youtube.com/v/zvd3kaupZ60&#038;hl=en_US&#038;fs=1&#038;rel=0"></param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param><embed src="http://www.youtube.com/v/zvd3kaupZ60&#038;hl=en_US&#038;fs=1&#038;rel=0" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="160" height="130"></embed></object></div>
<p>Ok, here's something you'll want to refer to daily... the current status of the jQuery 1.4 "TODO list", or as I like to call it, "<a href="http://dev.jquery.com/report/37">Report 37</a>". Usually when people on the jQuery dev lists ask "When will jQuery 1.4 be ready?" they are met with a resigned (<em>resigned</em> not <em>resiged</em>) answer: "When it's ready". But we don't have to take that kind of glib-ness anymore...</p>
<p><span id="more-1326"></span>Now we can go and consult good ol' Report 37 any time we need an ETA on 1.4. The method is simple: when all the red and white stripes turn light blue - then jQuery's ready to go! Of course, looking at all those lines takes up precious time and brain space - so I've compacted the data into a single image, so you can see how things are going at a glance.</p>
<p>Assuming this page has completed loading without JavaScript errors (a big assumption), you should see the Licorice Allsort graph to the right. The black lines mark the different components of the jQuery build: Ajax, Core, Event, FX, etc... The coloured lines are the status of the tickets. We want everything to turn blue, if only so there isn't so much pink on my blog.</p>
<p>To make the pretty pictures, I grab the report once a day, and dump it on my server. Then your browser goes all jQuery on it - loading it in and extracting relevant colour information. Then the super awesome <a href="http://raphaeljs.com/">Raphael SVG library</a> makes some pixels, and we all have a cup of tea.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.mrspeaker.net/2009/11/20/the-road-to-jquery-1-4-at-a-glance/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Adding &#8220;1UP notification&#8221; with jQuery</title>
		<link>http://www.mrspeaker.net/2009/11/16/1up-notification/</link>
		<comments>http://www.mrspeaker.net/2009/11/16/1up-notification/#comments</comments>
		<pubDate>Mon, 16 Nov 2009 06:56:56 +0000</pubDate>
		<dc:creator>Mr Speaker</dc:creator>
				<category><![CDATA[jQuery]]></category>

		<guid isPermaLink="false">http://www.mrspeaker.net/?p=1213</guid>
		<description><![CDATA[Now, as many of you know, I'm a big fan of taking interactions from retro gaming and attempting to squish them onto the page as standard UI elements. If I had my way, all sites would look like BMX Simulator from the C64. With that in mind... today something great happened. A win for old-school-gaming-as-ui-elements [...]]]></description>
			<content:encoded><![CDATA[<p><img src="/images/marioscore.png" class="frame-right" alt="mario score" />Now, as many of you know, I'm a <em>big</em> fan of taking interactions from retro gaming and attempting to squish them onto the page as standard UI elements. If I had my way, <em>all</em> sites would look like BMX Simulator from the C64. With that in mind... today something great happened. A win for old-school-gaming-as-ui-elements unmatched since CSS sprites were invented: <a href="http://adactio.com/journal/1626/">Jeremy Keith's 1UP notifications</a>! Don't simply let your user know they've "added a friend", let them feel like they "added a friend" <em>AND</em> scored 1000 points! 1UP notifications just <em>have</em> to storm the web with their awesomeness, and we need to do our best to help them.</p>
<div id="oneupTest"><span>Get some points:</span><span id="btnScore">GO!</span><span id="txtScore">1000</span></div>
<p><span id="more-1213"></span>Of course, you won't have "1000" popping up... you'll have "added" or "removed" or "dugggg" or something a bit useful to the end user. I don't care about end users, so <em>I'll</em> have "1000".</p>
<p>In the spirit of trying to get the effect to take over the web, I thought I'd throw together a jQuery plugin for sticking them on your site. The <a href="http://www.mrspeaker.net/dev/jq/jquery.oneup.js">jquery.oneup.js plugin</a> is very straightforward - it just animates an element upwards while fading out: 1UP style! To use it, just make your typical notification element <code>position:relative</code>, or <code>position:absolute</code> - whatever it takes to make it movable! (I'll fix this in the next version). For the demo, I've styled my notification message like so:</p>
<pre><code>...
&lt;input type="submit" id="go" value="go" /&gt;
&lt;span id="loadn"&gt;load&lt;/span&gt;
...
#loadn{
	position:relative;
	left:-30px;
	top:-4px;
	display:none;
}</pre>
<p></code>The element then sits "invisibled" over the "go" button, ready to fly... Next we wire up our 1UP functionality with the plugin:<br />
<code>
<pre>$("#go").click(function(){
	$("#loadn").oneUp();
});</code></pre>
<p>YES! That is so cool: check it <a href="http://www.mrspeaker.net/dev/jq/1UP/">in action</a>. The plugin accepts parameters <code>speed</code> (as a jQuery time - like, 'slow', 'fast' or 1000) and <code>distance</code> (how many pixels it travels upwards). You can also specify a callback if you need to do something after the notification completes (like in the demo).</p>
<p>Well, I'm pretty stoked with this turn of events. I've got to go back through every single site I've ever done and add way-too-many of these lil' fellows in. The <a href="http://www.mrspeaker.net/dev/jq/jquery.oneup.js">jquery.oneup.js</a> plugin needs a bit of work: so it handles positioning all by itself, and so forth... I'll let you know as soon as that's done. But in the mean time, I've got a highscore to go beat...</p>
]]></content:encoded>
			<wfw:commentRss>http://www.mrspeaker.net/2009/11/16/1up-notification/feed/</wfw:commentRss>
		<slash:comments>9</slash:comments>
		</item>
		<item>
		<title>Critical jQuery Info: How to pronounce &#8220;live&#8221;</title>
		<link>http://www.mrspeaker.net/2009/11/12/how-to-pronounce-live/</link>
		<comments>http://www.mrspeaker.net/2009/11/12/how-to-pronounce-live/#comments</comments>
		<pubDate>Thu, 12 Nov 2009 05:00:12 +0000</pubDate>
		<dc:creator>Mr Speaker</dc:creator>
				<category><![CDATA[jQuery]]></category>
		<category><![CDATA[Nerd]]></category>

		<guid isPermaLink="false">http://www.mrspeaker.net/?p=1165</guid>
		<description><![CDATA[After weeks of debate an answer has emerged. Live rhymes with "jive"? Or live rhymes with "give"?... that was the discussion point that was starting to turn ugly... In the live/jive corner: the "live" event is always on - like a live broadcast. In the live/give corner: the corresponding remove event is called "die", so [...]]]></description>
			<content:encoded><![CDATA[<p>After weeks of debate an answer has emerged. Live rhymes with "jive"? Or live rhymes with "give"?... that was the discussion point that was starting to turn ugly... In the live/jive corner: the "live" event is always on - like a live broadcast. In the live/give corner: the corresponding remove event is called "die", so it's "live &#038; die".</p>
<p>After finally getting fed up of saying "...just use the live/live event", <a href="http://www.twitter.com/twalve">@twalve</a> realised that our heros are merely a single tweet away and hit up <a href="http://brandonaaron.net/">Brandon Aaron</a> for the answer... and here it is:</p>
<p><span id="more-1165"></span></p>
<blockquote><p><a href="http://twitter.com/brandonaaron/status/5639993923">live as in "live broadcast" :)</a></p></blockquote>
<p>I'll sleep well tonight.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.mrspeaker.net/2009/11/12/how-to-pronounce-live/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Using jQuery on JavaScript objects (Part 1)</title>
		<link>http://www.mrspeaker.net/2009/10/28/using-jquery-on-javascript-objects/</link>
		<comments>http://www.mrspeaker.net/2009/10/28/using-jquery-on-javascript-objects/#comments</comments>
		<pubDate>Tue, 27 Oct 2009 23:34:19 +0000</pubDate>
		<dc:creator>Mr Speaker</dc:creator>
				<category><![CDATA[Javascript]]></category>
		<category><![CDATA[jQuery]]></category>

		<guid isPermaLink="false">http://www.mrspeaker.net/?p=1112</guid>
		<description><![CDATA[Today I was trying to decouple some JavaScript classes in a game prototype I've been working on. I didn't want to get into implementing some kind of interface behaviour, and so I thought about a simple Observer pattern. There are a bunch of solutions around the tubes (and indeed I'll probably use one of them) [...]]]></description>
			<content:encoded><![CDATA[<p>Today I was trying to decouple some JavaScript classes in a game prototype I've been working on. I didn't want to get into implementing some kind of interface behaviour, and so I thought about a simple Observer pattern. There are a bunch of solutions around the tubes (and indeed I'll probably use one of them) but I started wishing I could just use jQuery's custom events directly on my JavaScript classes.</p>
<p>This idea seemed pretty wacky to me, and made me smile: jQuery events attach themselves to <em>DOM</em> elements - wrapping a JavaScript object in the jQuery selector seemed ludicrous - I mean, should I be able to do $(class).hide()?! No, of course not. But none the less, my curiosity got the better of me, and I tried this lil' snippet:<br />
<span id="more-1112"></span></p>
<pre><code>function cPerson( name, age ){
	this.name = name;
	this.age = age;

	$( this ).bind( "yell", function(){
		alert( this.name + " is " + this.age + " years old!!" );
	})
}
var person1 = new cPerson( "Bob", 32 );
$( person1 ).trigger( "yell" );</code></pre>
<p>To my astonishment, it worked! The custom event fired! I quickly delved into the jQuery source to find out how it handled the object. Skipping through all the regular selector handlers, our object gets converted into an array like so:</p>
<pre><code>return this.setArray(jQuery.isArray( selector ) ?
			selector :
			jQuery.makeArray(selector));</code></pre>
<p>Which is also how other objects like "document" and "window" get handled. Ahh yeah, document and window... it's not that ludicrous after all. I tested it on functions which, I reasoned, should also work - but alas there is a path in the jQuery selector code that says:</p>
<pre><code>if ( jQuery.isFunction( selector ) )
	return jQuery( document ).ready( selector )</code></pre>
<p>So functions fall through to the document.ready shortcut code. Ah well.</p>
<p>But wait, what else can we do with a wrapped instance of an object? Obviously "slideDown()" is a bit stupid? And clone(), appendTo(), wrapAll() etc. don't make sense... how abooouut... <em>data</em>? or plugins?!</p>
<pre><code>$.fn.misterise = function(){
  	return this.each(function() {
 		this.name = "Mr " + this.name;
		this.name += $(this).data( "surname" ) || "";
	});
};

var person1 = new cPerson( "Bob", 32 );
var person2 = new cPerson( "Dave", 27 );
var peeps = [ person1, person2 ];

$( peeps )
	.data( "surname", " Dobalina" )
	.misterise()
	.trigger( "yell" );</code></pre>
<p>And out pops Mr Bob Dobalina &#038; Mr Dave Dobalina! I'm not sure of any practical purpose for this odd bit of functionality. Perhaps some kind of AOP meta-data system or, um, no... I dunno. Here's a plugin for executing methods on an object by name:</p>
<pre><code>
$.fn.go = function( funcName ){
	return this.each(function(){
		if( $.isFunction( this[ funcName ] ) ){
			this[ funcName ]();
		}
	});
};
</code></pre>
<p>That's pretty stupid and cool. Using a plugin against your JavaScript classes instead of a simple method call will most likely get you killed by your colleagues, but hey, it keeps things looking jQuery-ish. And that's the important thing.</p>
<p><strong>Update:</strong> Futher investigation has lead to some interesting discoveries... <a href="http://www.mrspeaker.net/2009/11/14/selecting-javascript-objects-with-jquery/">Go have a read!</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.mrspeaker.net/2009/10/28/using-jquery-on-javascript-objects/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
	</channel>
</rss>

