<?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>scriptNode &#187; lab</title>
	<atom:link href="http://scriptnode.com/tag/lab/feed/" rel="self" type="application/rss+xml" />
	<link>http://scriptnode.com</link>
	<description>Tips and tricks for web developers.</description>
	<lastBuildDate>Tue, 01 Sep 2009 18:46:41 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.8.4</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Simple Loading Bar</title>
		<link>http://scriptnode.com/article/simple-loading-bar/</link>
		<comments>http://scriptnode.com/article/simple-loading-bar/#comments</comments>
		<pubDate>Mon, 03 Aug 2009 06:56:36 +0000</pubDate>
		<dc:creator>Matt Hackett</dc:creator>
				<category><![CDATA[Novice]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[lab]]></category>
		<category><![CDATA[script-sunday]]></category>

		<guid isPermaLink="false">http://scriptnode.com/?p=316</guid>
		<description><![CDATA[
Haven&#8217;t had a Script Sunday for a while, so here&#8217;s a quick, simple script for you. Ever see those Loading … overlay images and wonder if JavaScript can handle it? Turns out it&#8217;s extremely simple:


animate = (function() {
  var busy;
  return function(id) {
    if (busy) return;
    busy [...]]]></description>
			<content:encoded><![CDATA[<p>
Haven&#8217;t had a <a href="/tag/script-sunday/">Script Sunday</a> for a while, so here&#8217;s a quick, simple script for you. Ever see those <strong>Loading …</strong> overlay images and wonder if JavaScript can handle it? Turns out it&#8217;s extremely simple:
</p>
<p><textarea class="javascript" cols="50" name="code" rows="10"><br />
animate = (function() {</p>
<p>  var busy;</p>
<p>  return function(id) {</p>
<p>    if (busy) return;</p>
<p>    busy = true;<br />
    var width = 0;<br />
    var interval = setInterval(function() {</p>
<p>      var el = document.getElementById(id);<br />
      el.innerHTML = &#8216;@%
<div style="width: @px;"><span>@%</span></div>
<p>&#8216;.replace(/@/g, width);</p>
<p>      if (width++ >= 100) {<br />
        busy = false;<br />
        clearInterval(interval);<br />
      }</p>
<p>    }, 50);</p>
<p>  };</p>
<p>})();<br />
</textarea></p>
<p>
You can view this by itself <a href="/lab/bar/">in the lab</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://scriptnode.com/article/simple-loading-bar/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>JSQL: JavaScript Query Language</title>
		<link>http://scriptnode.com/article/jsql-javascript-query-language/</link>
		<comments>http://scriptnode.com/article/jsql-javascript-query-language/#comments</comments>
		<pubDate>Mon, 23 Mar 2009 06:12:20 +0000</pubDate>
		<dc:creator>Matt Hackett</dc:creator>
				<category><![CDATA[Advanced]]></category>
		<category><![CDATA[github]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[jquery]]></category>
		<category><![CDATA[lab]]></category>
		<category><![CDATA[script-sunday]]></category>

		<guid isPermaLink="false">http://scriptnode.com/?p=286</guid>
		<description><![CDATA[About JSQL

When I started my new job, I had to make the transition from YUI to jQuery. I&#8217;d seen some jQuery code before (in fact, its terseness and use of $ as both an object and a function were easy to spot), but I wasn&#8217;t familiar with it. I actually thought that the query part [...]]]></description>
			<content:encoded><![CDATA[<h3>About JSQL</h3>
<p>
When I started <a href="http://richter.paletteswap.com/why-i-left-yahoo-for-a-startup/">my new job</a>, I had to make the transition from <a href="http://developer.yahoo.com/yui/">YUI</a> to <a href="http://jquery.com/">jQuery</a>. I&#8217;d seen some jQuery code before (in fact, its terseness and use of <code>$</code> as both an object and a function were easy to spot), but I wasn&#8217;t familiar with it. I actually thought that the <em>query</em> part of jQuery meant there was some kind of <a href="http://mysql.com/">Standard Query Language</a> interface. There isn&#8217;t, but there is a really cool <a href="http://www.css3.info/">CSS3</a> selector instead.
</p>
<p>
Turns out, I was a little disappointed; I wanted to use something query-based. So, I started to throw this script together. I call it <acronym title="JavaScript Query Language">JSQL</acronym>. Below are some quick examples of what it looks like in action:
</p>
<p><script src="/assets/js/jsql/jsql-min.js" type="text/javascript"></script></p>
<p><textarea class="javascript" cols="50" name="code" rows="10"><br />
var results = JSQL(&#8217;SELECT * FROM #ft WHERE nodeName = &#8220;LI&#8221;);<br />
</textarea></p>
<p>
JSQL always returns an object with an <code>error</code> property that&#8217;s either <code>Boolean false</code> or a <code>String</code> stating what error occurred (for example, &#8220;Unknown command UPDAT3&#8243;). If it successfully retrieves or operates on elements, it returns a <code>count:Number</code> property with the number of elements and an <code>elements:Array</code> property with those elements.
</p>
<p>
Here are some interactive examples:
</p>
<h3>Example 1: Checkboxes</h3>
<div class="section" id="jsql-example-1">
<div>
<input type="checkbox" value=""/> Option number 1
		</div>
<div>
<input type="checkbox" value=""/> Option number 2
		</div>
<div>
<input type="checkbox" value=""/> Option number 3
		</div>
</p></form>
</div>
<p><textarea class="javascript" cols="50" name="code" rows="10"><br />
JSQL(&#8217;UPDATE #jsql-example-1 SET checked = true WHERE type = &#8220;checkbox&#8221;&#8216;);<br />
</textarea></p>
<p>
<button id="jsql-button-1">Set Checked</button>
</p>
<p><script type="text/javascript">
document.getElementById('jsql-button-1').onclick = function() {
JSQL('UPDATE #jsql-example-1 SET checked = true WHERE type = "checkbox"');
};
</script><br />
<textarea class="javascript" cols="50" name="code" rows="10"><br />
JSQL(&#8217;UPDATE #jsql-example-1 SET checked = false WHERE type = &#8220;checkbox&#8221;&#8216;);<br />
</textarea></p>
<p>
<button id="jsql-button-1a">Uncheck</button>
</p>
<p><script type="text/javascript">
document.getElementById('jsql-button-1a').onclick = function() {
JSQL('UPDATE #jsql-example-1 SET checked = false WHERE type = "checkbox"');
};
</script></p>
<h3>Example 2: Form Validation</h3>
<div class="section" id="jsql-example-2">
<p>
			First name:</p>
<input type="text" value=""/>
<p>
			Last name:</p>
<input type="text" value=""/>
<p>
			Email:</p>
<input type="text" value=""/>
</div>
<p><textarea class="javascript" cols="50" name="code" rows="10"><br />
JSQL(&#8217;UPDATE #jsql-example-2 SET parentNode.className = &#8220;error&#8221; WHERE value = &#8220;&#8221;&#8216;);<br />
</textarea></p>
<p>
<button id="jsql-button-2">Highlight empty fields</button>
</p>
<p><script type="text/javascript">
document.getElementById('jsql-button-2').onclick = function() {
JSQL('UPDATE #jsql-example-2 SET parentNode.className = "error" WHERE value = ""');
};
</script><br />
<textarea class="javascript" cols="50" name="code" rows="10"><br />
JSQL(&#8217;UPDATE #jsql-example-2 SET parentNode.className = &#8220;&#8221; WHERE value = &#8220;&#8221;&#8216;);<br />
</textarea></p>
<p>
<button id="jsql-button-2a">Reset</button>
</p>
<p><script type="text/javascript">
document.getElementById('jsql-button-2a').onclick = function() {
JSQL('UPDATE #jsql-example-2 SET parentNode.className = "" WHERE value = ""');
};
</script></p>
<h3>Example 3: Removing Elements</h3>
<div class="section" id="jsql-example-3">
<strong>Lorem</strong> Ipsum is simply dummy text of the <strong>printing and</strong> typesetting industry. <strong>Lorem</strong> Ipsum has been the <strong>industry&#8217;s</strong> standard dummy text <strong>ever</strong> since the 1500s, when an unknown printer took a galley of type and scrambled it to make a <strong>type specimen</strong> book. It has survived not only <strong>five</strong> centuries, but also the leap into <strong>electronic</strong> typesetting<strong>, remaining essentially unchanged</strong>. It was popularised in the 1960s with the release of <strong>Letraset</strong> sheets containing <strong>Lorem Ipsum</strong> passages, and more recently with <strong>desktop publishing</strong> software like Aldus PageMaker including versions of <strong>Lorem</strong> Ipsum.
</div>
<p><textarea class="javascript" cols="50" name="code" rows="10"><br />
JSQL(&#8217;DELETE FROM #jsql-example-3 WHERE nodeName = &#8220;STRONG&#8221;&#8216;);<br />
</textarea></p>
<p>
<button id="jsql-button-3">Remove strong tags</button>
</p>
<p><script type="text/javascript">
document.getElementById('jsql-button-3').onclick = function() {
JSQL('DELETE FROM #jsql-example-3 WHERE nodeName = "STRONG"');
};
</script></p>
<p>
In the spirit of jQuery, I also stuck in a quick <code>each</code> method which you can use to iterate through the returned elements immediately instead of setting up your own loop. The context is the current element (like jQuery) and the return value is still the same:</p>
<h3>Example 4: Selecting Elements</h3>
<div class="section" id="jsql-example-4">
Give him that <em>gun</em>. Give him <em>ALL</em> the guns.
</div>
<p><textarea class="javascript" cols="50" name="code" rows="10"><br />
JSQL(&#8221;SELECT * FROM #jsql-example-4 WHERE nodeName = &#8216;EM&#8217;&#8221;).each(function() {<br />
	this.style.background = &#8216;#ffff00&#8242;;<br />
});<br />
</textarea></p>
<p>
<button id="jsql-button-4">Select &amp; Operate</button>
</p>
<p><script type="text/javascript">
document.getElementById('jsql-button-4').onclick = function() {
JSQL("SELECT * FROM #jsql-example-4 WHERE nodeName = 'EM'").each(function() {
	this.style.background = '#ffff00';
});
};
</script><br />
<textarea class="javascript" cols="50" name="code" rows="10"><br />
JSQL(&#8221;SELECT * FROM #jsql-example-4 WHERE nodeName = &#8216;EM&#8217;&#8221;).each(function() {<br />
	this.style.background = &#8221;;<br />
});<br />
</textarea></p>
<p>
<button id="jsql-button-4a">Undo</button>
</p>
<p><script type="text/javascript">
document.getElementById('jsql-button-4a').onclick = function() {
JSQL("SELECT * FROM #jsql-example-4 WHERE nodeName = 'EM'").each(function() {
	this.style.background = '';
});
};
</script></p>
<p>
I started coding this several months ago, and just recently decided to revisit it. I found the code hard to read myself when making some modifications before publishing it here. That typically means it&#8217;s poorly written. And I&#8217;m admittedly lousy at writing parsing code&#8230; so there&#8217;s that. I also doubt it&#8217;s realistic for any real-world websites (other libraries handle those jobs quite well), but I thought it would be fun to play with.
</p>
<p>
Some noticeable features lacking are equivalents to <code>ALTER</code> and <code>INSERT INTO</code>. I&#8217;ve also got it <a href="http://github.com/richtaur/jsql/tree/master">up on GitHub</a>, so feel free to fork it, and maybe add those methods yourself!
</p>
<ul>
<li><a href="/assets/js/jsql/jsql.js">[Download jsql.js]</a> (11k)</li>
<li><a href="/assets/js/jsql/jsql-min.js">[Download jsql-min.js]</a> (3,661 bytes)</li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://scriptnode.com/article/jsql-javascript-query-language/feed/</wfw:commentRss>
		<slash:comments>9</slash:comments>
		</item>
		<item>
		<title>Spacius! Source Code</title>
		<link>http://scriptnode.com/article/spacius-source-code/</link>
		<comments>http://scriptnode.com/article/spacius-source-code/#comments</comments>
		<pubDate>Tue, 10 Mar 2009 05:52:23 +0000</pubDate>
		<dc:creator>Matt Hackett</dc:creator>
				<category><![CDATA[Advanced]]></category>
		<category><![CDATA[code-style]]></category>
		<category><![CDATA[games]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[just-for-fun]]></category>
		<category><![CDATA[lab]]></category>
		<category><![CDATA[tutorials]]></category>

		<guid isPermaLink="false">http://scriptnode.com/?p=278</guid>
		<description><![CDATA[
I&#8217;ve been meaning to &#8220;release&#8221; this for quite some time now, but I wanted to do it in small doses, with in-depth explanations of the code. Making a game can be somewhat overwhelming, but it&#8217;s just like any other large task: if you break it up into smaller pieces, it becomes much easier to manage.


But [...]]]></description>
			<content:encoded><![CDATA[<p>
I&#8217;ve been meaning to &#8220;release&#8221; this for quite some time now, but I wanted to do it in small doses, with in-depth explanations of the code. Making a game can be somewhat overwhelming, but it&#8217;s just like any other large task: if you break it up into smaller pieces, it becomes much easier to manage.
</p>
<p>
But time is a commodity nowadays. I&#8217;ve got way less time to write, and when I do, I&#8217;d rather be writing <em>code</em> than tutorials (or honestly, <a href="http://raptr.com/richtaur"><em>playing</em> video games</a>). Sorry about that, but I hope the (well-commented!) source will help those of you out there who&#8217;d like to contribute to the <a href="http://games.nihilogic.dk/">slowly growing world of DHTML games</a>.
</p>
<p>
You&#8217;ll notice that this code is <a href="/article/spacius-a-space-adventure/">over 6 months old</a>. And I&#8217;m the kind of developer who constantly updates his <a href="/tag/code-style/">style, methods and patterns</a>. Given that, there may very well be many mistakes or bad practices in here, some of which I may have improved upon by now, but others maybe not. Either way, feel free to comment on them, and I&#8217;ll answer any questions as well.
</p>
<p>
Thanks for checking it out, and please be good to it. I&#8217;d love to know about any projects created with this source as a basis, and would appreciate links back here. Also please don&#8217;t claim it as your own, that&#8217;s not cool.
</p>
<div class="section">
For now I am hosting the source code with <a href="http://github.com/richtaur/spacius-/tree/master">GitHub</a>.
</div>
<p>
Enjoy!</p>
]]></content:encoded>
			<wfw:commentRss>http://scriptnode.com/article/spacius-source-code/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Multiline Strings in JavaScript</title>
		<link>http://scriptnode.com/article/multiline-strings-in-javascript/</link>
		<comments>http://scriptnode.com/article/multiline-strings-in-javascript/#comments</comments>
		<pubDate>Wed, 22 Oct 2008 00:17:48 +0000</pubDate>
		<dc:creator>Matt Hackett</dc:creator>
				<category><![CDATA[Intermediate]]></category>
		<category><![CDATA[code-style]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[lab]]></category>
		<category><![CDATA[php]]></category>
		<category><![CDATA[tutorials]]></category>

		<guid isPermaLink="false">http://scriptnode.com/?p=217</guid>
		<description><![CDATA[
The ability to write multiline strings is a common feature in many languages. It promotes readability and is often much cleaner than the alternatives. Here&#8217;s a typically ugly example of string concatenation in PHP:


$my_string = &#8220;This string\n&#8221;;
$my_string .= &#8220;spans multiple\n&#8221;;
$my_string .= &#8220;lines.\n&#8221;;


Thankfully, PHP has the benefit of heredoc syntax, which makes code like this much [...]]]></description>
			<content:encoded><![CDATA[<p>
The ability to write multiline strings is a common feature in many languages. It promotes readability and is often much cleaner than the alternatives. Here&#8217;s a typically ugly example of string concatenation in <a href="http://us2.php.net/" title="PHP Hypertext Preprocessor">PHP</a>:
</p>
<p><textarea class="php" cols="50" name="code" rows="10"><br />
$my_string = &#8220;This string\n&#8221;;<br />
$my_string .= &#8220;spans multiple\n&#8221;;<br />
$my_string .= &#8220;lines.\n&#8221;;<br />
</textarea></p>
<p>
Thankfully, PHP has the benefit of <a href="http://www.php.net/manual/en/language.types.string.php#language.types.string.syntax.heredoc">heredoc syntax</a>, which makes code like this much easier to read, write and maintain:
</p>
<p><textarea class="php" cols="50" id="heredoc-example" name="code" rows="10"><br />
$my_string = &lt;&lt;&lt;MYSTRING<br />
This string<br />
spans multiple<br />
lines.<br />
MYSTRING;<br />
</textarea></p>
<h3>E4X</h3>
<p>
But what about <a href="http://developer.mozilla.org/en/JavaScript">JavaScript</a>? There is no native heredoc support, but there are some other workarounds that can be used. The first I&#8217;ll offer up is <a href="http://en.wikipedia.org/wiki/E4X">ECMAScript for XML (E4X)</a>.
</p>
<p><textarea class="javascript" cols="50" name="code" rows="10"><br />
var myString = &#8221; + &lt;myString&gt;&lt;![CDATA[This string<br />
spans multiple<br />
lines.<br />
]]&gt;&lt;/myString&gt;;<br />
</textarea></p>
<p>
The first line in the above example is a bit confusing. The <acronym title="Extensible Markup Language">XML</acronym> will return an xml object by default, but what we want is a <code>String</code>. We can type the return as a <code>String</code> by concatenating to an empty string (<code>''</code>).
</p>
<p>
Next, an element must be wrapped around the <code>CDATA</code> to trigger the <acronym>XML</acronym> parser. This step is similar to PHP&#8217;s <a href="#heredoc-example">heredoc syntax</a> in that it requires an identical beginning and ending identifier.
</p>
<p>
You can test this yourself <a href="/lab/e4x/">in the lab</a>.<br />
Currently, it looks like only <a href="http://developer.mozilla.org/En/Gecko">Gecko</a> browsers (such as <a href="http://www.mozilla.com/en-US/firefox/">Firefox</a> and <a href="http://caminobrowser.org/">Camino</a>) support E4X. This obviously doesn&#8217;t include <a href="http://browsehappy.com/why/">Internet Explorer</a>, which is (unfortunately) often a large portion of most websites&#8217; user bases. While this workaround is interesting, it&#8217;s definitely not realistic to assume all of your users are using Firefox, <a href="http://xkcd.com/111/">despite its rising popularity</a> (also, it will <a href="http://tr.im/hez">fail to validate</a>).
</p>
<h3>Hidden Element Hack</h3>
<p>
Another workaround I&#8217;ve seen is to place the string inside of an element (often hidden from view) and to read it in via JavaScript. Here&#8217;s an example:
</p>
<p><textarea class="php" cols="50" name="code" rows="10"><br />
/* Based on this markup:<br />
&lt;div id=&#8221;multilines&#8221; style=&#8221;display: none;&#8221;&gt;<br />
This string<br />
spans multiple<br />
lines.<br />
&lt;/div&gt;<br />
*/<br />
var myString = document.getElementById(&#8217;multilines&#8217;);<br />
</textarea></p>
<p>
This solution is clever, but definitely a hack job: not very clean, and with a bad <a href="http://www.w3.org/WAI/intro/accessibility.php">accessibility case</a>. The primary issue though is that it doesn&#8217;t completely solve the problem. Markup is needed to interact with the JavaScript code, so to use this solution one couldn&#8217;t maintain a completely independent <code>.js</code> file.
</p>
<h3>Escaping linebreaks</h3>
<p>
Another solution is very simply just to escape line breaks:
</p>
<p><textarea class="php" cols="50" name="code" rows="10"><br />
var myString = &#8220;This string\<br />
spans multiple\<br />
lines.&#8221;;<br />
</textarea></p>
<p>
By escaping the linebreak, you&#8217;re free to continue the string on the next line (<em><strong>note:</strong> this doesn&#8217;t include spaces, so if you want to separate words, you&#8217;ll need to begin each new line with a space</em>). This solution is not as attractive as the E4X workaround, but has the benefit of being perfectly cross-browser compatible. Therefore, it looks like it&#8217;s currently the best method available.
</p>
<p>
Do you know of any other workarounds? If so, please let me know in the comments section.</p>
]]></content:encoded>
			<wfw:commentRss>http://scriptnode.com/article/multiline-strings-in-javascript/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>twittertyper</title>
		<link>http://scriptnode.com/article/twittertyper/</link>
		<comments>http://scriptnode.com/article/twittertyper/#comments</comments>
		<pubDate>Wed, 10 Sep 2008 01:11:51 +0000</pubDate>
		<dc:creator>Matt Hackett</dc:creator>
				<category><![CDATA[Intermediate]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[just-for-fun]]></category>
		<category><![CDATA[lab]]></category>
		<category><![CDATA[yui]]></category>

		<guid isPermaLink="false">http://scriptnode.com/?p=157</guid>
		<description><![CDATA[



I unfortunately am not allowed to participate, but in anticipation of Yahoo!&#8217;s Hack Day 2008, I put together a little app I&#8217;ll hopefully be able to port to YAP: twittertyper!


The concept is very simple. twittertyper displays the latest tweet from Twitter. To read the next one, first type out the tweet. The text is highlighted [...]]]></description>
			<content:encoded><![CDATA[<p class="before">
<a href="/lab/twittertyper/"><img alt="twittertyper" src="http://scriptnode.com/lab/twittertyper/logo.png"/></a>
</p>
<p>
I unfortunately am not allowed to participate, but in anticipation of Yahoo!&#8217;s <a href="http://developer.yahoo.net/hackday/">Hack Day 2008</a>, I put together a little app I&#8217;ll hopefully be able to port to <a href="http://developer.yahoo.com/searchmonkey/" title="Yahoo! Application Platform">YAP</a>: <a href="/lab/twittertyper/">twittertyper</a>!
</p>
<p>
The concept is very simple. <strong>twittertyper</strong> displays the latest tweet from <a href="http://twitter.com">Twitter</a>. To read the next one, first <strong>type out the tweet</strong>. The text is highlighted as you go. If you come across a character your keyboard (or operating system) won&#8217;t let you type, just press <code>Esc</code> to move on to the next character.
</p>
<p>
<strong>twittertyper</strong> currently just pulls in from the <a href="http://twitter.com/public_timeline">public timeline</a>; no authentication is supported to pull from <em>your</em> timeline (maybe in a future version). This mini-app is built on <a href="http://developer.yahoo.com/yui/" title="Yahoo! User Interface Library">YUI</a>. Source code (uncompressed) is <a href="/lab/twittertyper/tt.js">free to peruse</a>.
</p>
<p>
<a href="/lab/twittertyper/">Try it out!</a>
</p>
<p>
<em><strong>Note:</strong> If you use Twitter, I&#8217;m sure you&#8217;re used to it being down. Errors happen often, but <strong>twittertyper</strong> attempts to handle them somewhat gracefully. Usually a page reload should suffice.</em></p>
]]></content:encoded>
			<wfw:commentRss>http://scriptnode.com/article/twittertyper/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Shark!</title>
		<link>http://scriptnode.com/article/shark/</link>
		<comments>http://scriptnode.com/article/shark/#comments</comments>
		<pubDate>Sun, 03 Aug 2008 10:56:42 +0000</pubDate>
		<dc:creator>Matt Hackett</dc:creator>
				<category><![CDATA[Advanced]]></category>
		<category><![CDATA[games]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[just-for-fun]]></category>
		<category><![CDATA[lab]]></category>
		<category><![CDATA[script-sunday]]></category>
		<category><![CDATA[yui]]></category>

		<guid isPermaLink="false">http://scriptnode.com/?p=48</guid>
		<description><![CDATA[
Well, this year&#8217;s Shark Week is over. In its memory, I offer up a script that makes sharks swim around on the screen. You should see a few sharks swimming about right now! Here&#8217;s the source code:


/**
 * Global Shark constructor
 * Options for ops: dir, speed, url, x, y, zIndex
 * @constructor
 * @public
 [...]]]></description>
			<content:encoded><![CDATA[<p>
Well, this year&#8217;s <a href="http://discovery.com/sharkweek/">Shark Week</a> is over. In its memory, I offer up a script that makes sharks swim around on the screen. You should see a few sharks swimming about right now! Here&#8217;s the source code:
</p>
<p><textarea class="javascript" cols="50" name="code" rows="10"><br />
/**<br />
 * Global Shark constructor<br />
 * Options for ops: dir, speed, url, x, y, zIndex<br />
 * @constructor<br />
 * @public<br />
 */<br />
Shark = function(ops) {</p>
<p>	var Y = YAHOO.util,<br />
		DEFAULT_SPEED = 2,<br />
		DEFAULT_ZINDEX = 1000,<br />
		DELAY = 25,<br />
		LEFT = &#8216;l&#8217;,<br />
		RIGHT = &#8216;r&#8217;,<br />
		SCREEN_WIDTH = Y.Dom.getViewportWidth(),<br />
		SCREEN_HEIGHT = Y.Dom.getViewportHeight(),<br />
		SHARK_WIDTH = 242,<br />
		SHARK_HEIGHT = 82;</p>
<p>	var interval,<br />
		that = this;</p>
<p>	that.active = true;<br />
	that.dir = LEFT;<br />
	that.el = {};<br />
	that.onOutLeft = function(){};<br />
	that.onOutRight = function(){};<br />
	that.x = 0;<br />
	that.y = 0;</p>
<p>	/**<br />
	 * Initializes the shark variables<br />
	 * @private<br />
	 */<br />
	var init = function() {</p>
<p>		ops = ops || {};<br />
		ops.speed = ops.speed || rand(DEFAULT_SPEED, (DEFAULT_SPEED * 2));<br />
		ops.url = ops.url || &#8216;./&#8217;;<br />
		ops.zIndex = ops.zIndex || DEFAULT_ZINDEX;</p>
<p>		if (ops.dir) {<br />
			that.dir = ops.dir;<br />
		} else {<br />
			that.dir = [LEFT, RIGHT][rand(0, 1)];<br />
		}</p>
<p>		if (ops.x === undefined) {<br />
			if (that.dir == LEFT) {<br />
				that.x = (SCREEN_WIDTH &#8211; 1);<br />
			} else {<br />
				that.x = -SHARK_WIDTH;<br />
			}<br />
		} else {<br />
			that.x = ops.x;<br />
		}</p>
<p>		that.el = document.createElement(&#8217;div&#8217;);<br />
		that.el.className = &#8217;shark&#8217;; // Doesn&#8217;t do anything. Just in case you want to use it<br />
		that.el.style.position = &#8216;absolute&#8217;;<br />
		that.el.style.height = SHARK_HEIGHT + &#8216;px&#8217;;<br />
		that.el.style.zIndex = ops.zIndex;</p>
<p>		Y.Event.addListener(that.el, &#8216;click&#8217;, onclick);</p>
<p>		document.body.appendChild(that.el);<br />
		reset();</p>
<p>		if (ops.y !== undefined) {<br />
			that.y = ops.y<br />
			plot();<br />
		}</p>
<p>		that.start();</p>
<p>	};</p>
<p>	/**<br />
	 * Kills the shark<br />
	 * @param {Boolean} fade Whether to fade the shark in or not<br />
	 */<br />
	that.kill = function(fade) {</p>
<p>		that.active = false;</p>
<p>		var done = function() {<br />
			document.body.removeChild(that.el);<br />
			stop();<br />
		};</p>
<p>		if (fade) {</p>
<p>			var anim = new Y.Anim(that.el, {opacity : {to : 0}}, 0.5);</p>
<p>			anim.onComplete.subscribe(done);<br />
			anim.animate();</p>
<p>		} else {<br />
			done();<br />
		}</p>
<p>	};</p>
<p>	/**<br />
	 * Move the shark<br />
	 */<br />
	var move = function() {</p>
<p>		if (!that.active) {<br />
			return;<br />
		}</p>
<p>		if (that.dir == LEFT) {</p>
<p>			that.x -= ops.speed;</p>
<p>			if (that.x &lt; -SHARK_WIDTH) {<br />
				that.dir = RIGHT;<br />
				that.onOutLeft();<br />
				reset();<br />
			}</p>
<p>		} else {</p>
<p>			that.x += ops.speed;</p>
<p>			if (that.x &gt; (SCREEN_WIDTH &#8211; 1)) {<br />
				that.dir = LEFT;<br />
				that.x = (SCREEN_WIDTH &#8211; 1);<br />
				that.onOutRight();<br />
				reset();<br />
			}</p>
<p>		}</p>
<p>		if (that.x &gt; (SCREEN_WIDTH &#8211; SHARK_WIDTH)) {<br />
			that.el.style.width = (SHARK_WIDTH &#8211; (that.x &#8211; (SCREEN_WIDTH &#8211; SHARK_WIDTH))) + &#8216;px&#8217;;<br />
		} else {<br />
			that.el.style.width = SHARK_WIDTH + &#8216;px&#8217;;<br />
		}</p>
<p>		plot();</p>
<p>	};</p>
<p>	/**<br />
	 * Kills the shark. Note: intended to be overwritten<br />
	 */<br />
	var onclick = function() {<br />
		that.onclick();<br />
	};</p>
<p>	/**<br />
	 * Default onclick behavior<br />
	 */<br />
	that.onclick = function() {<br />
		that.kill(true);<br />
	};</p>
<p>	/**<br />
	 * Moves the shark element to the XY coordinates<br />
	 */<br />
	var plot = function() {<br />
		that.el.style.left = that.x + &#8216;px&#8217;;<br />
		that.el.style.top = that.y + &#8216;px&#8217;;<br />
	};</p>
<p>	/**<br />
	 * Returns a random number<br />
	 * @param {Number} from The starting point<br />
	 * @param {Number} to The stopping point<br />
	 * @return {Number} A random number within the range<br />
	 */<br />
	var rand = function(from, to) {<br />
		return (from + Math.floor((to &#8211; from + 1) * Math.random()));<br />
	}; </p>
<p>	/**<br />
	 * Sets the background based on direction and randomizes the Y position<br />
	 */<br />
	var reset = function() {</p>
<p>		that.el.style.background = &#8216;url(&#8217; + ops.url + &#8217;shark_&#8217; + that.dir + &#8216;.gif)&#8217;;<br />
		that.y = rand(0, (SCREEN_HEIGHT &#8211; SHARK_HEIGHT &#8211; 1));</p>
<p>		plot();</p>
<p>	};</p>
<p>	/**<br />
	 * Starts the move interval<br />
	 */<br />
	that.start = function() {</p>
<p>		if (interval) {<br />
			return;<br />
		}</p>
<p>		interval = setInterval(move, DELAY);</p>
<p>	};</p>
<p>	/**<br />
	 * Stops the move interval<br />
	 */<br />
	that.stop = function() {<br />
		if (interval) {<br />
			clearInterval(interval);<br />
			interval = false;<br />
		}<br />
	};</p>
<p>	init();</p>
<p>};<br />
</textarea></p>
<p>
You can create new sharks like this:
</p>
<p><textarea class="javascript" cols="50" name="code" rows="10"><br />
var myShark = new Shark();</p>
<p>// Or setup some basics, like having him swim to the left<br />
var anotherShark = new Shark({dir : &#8216;l&#8217;});<br />
anotherShark.onclick = function() {<br />
alert(&#8221;I&#8217;m a shaaaaaaark!&#8221;);<br />
myShark.kill(true); // Kill it with a fade<br />
};</p>
<p>// You may also want to host the shark images yourself:<br />
var hostedShark = new Shark({url : &#8216;http://mydomain.com/shark/&#8217;});<br />
</textarea></p>
<p>
The last example above shows setting a custom <acronym title="Uniform Resource Locator">URL</acronym> for the shark images. You can download those here:
</p>
<p>
<a href="/lab/shark/shark_l.gif"><img alt="Shark!" src="/lab/shark/shark_l.gif"/></a><br />
<a href="/lab/shark/shark_r.gif"><img alt="Shark!" src="/lab/shark/shark_r.gif"/></a>
</p>
<p>
<a class="after" href="/lab/shark/"><img alt="Shark!" src="/assets/img/shark_thumbnail.jpg"/></a><br />
There are a few different events you can subscribe to including <code>onclick</code>, <code>onOutLeft</code> and <code>onOutRight</code>, which I think are pretty self-explanatory.<br />
Using these events, I put together <a href="http://scriptnode.com/lab/shark/">a very simple game</a> involving sharks, clicking and hopelessly trying to save a doomed diver. The ocean graphics came from one of my <a href="http://csszengarden.com/?cssfile=http://www.css-praxis.de/cssocean/zenocean.css">favorite CSS Zen Garden examples</a>.
</p>
<p>
The shark script requires <a href="http://developer.yahoo.com/yui/">YUI</a> (Animation, DOM and Event). I&#8217;ve included it in the third download option below:
</p>
<ul>
<li><a href="/assets/js/shark/shark.js">[Download shark.js]</a> (3,747 bytes)</li>
<li><a href="/assets/js/shark/shark-min.js">[Download shark-min.js]</a> (1,550 bytes; compressed)</li>
<li><a href="/assets/js/shark/shark-min-yui.js">[Download shark-min-yui.js]</a> (46k; compressed with YUI)</li>
</ul>
<p>
I&#8217;d love to see if anybody else has cool ideas of what to do with the shark script!
</p>
<p><script src="/assets/js/shark/shark-min-yui.js" type="text/javascript"></script><br />
<script type="text/javascript">
(function() {
new Shark({url : '/lab/shark/'});
new Shark({url : '/lab/shark/'});
})();
</script></p>
]]></content:encoded>
			<wfw:commentRss>http://scriptnode.com/article/shark/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Spacius! A Space Adventure</title>
		<link>http://scriptnode.com/article/spacius-a-space-adventure/</link>
		<comments>http://scriptnode.com/article/spacius-a-space-adventure/#comments</comments>
		<pubDate>Tue, 08 Jul 2008 19:19:43 +0000</pubDate>
		<dc:creator>Matt Hackett</dc:creator>
				<category><![CDATA[Advanced]]></category>
		<category><![CDATA[games]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[just-for-fun]]></category>
		<category><![CDATA[lab]]></category>

		<guid isPermaLink="false">http://scriptnode.com/?p=38</guid>
		<description><![CDATA[



I must have been feeling nostalgic, missing my wasted hours playing old Nintendo games as a kid, because last weekend I put together Spacius! A Space Adventure. My goal was to make a fun, simple game using only JavaScript that would work in any browser. That&#8217;s right folks, this game was made using just div [...]]]></description>
			<content:encoded><![CDATA[<p>
<a href="/lab/spacius/"><img alt="Spacius! A Space Adventure" src="/assets/img/spacius-a-space-adventure/title.gif"/></a>
</p>
<p>
I must have been feeling nostalgic, missing my wasted hours playing <a href="http://gradius.classicgaming.gamespy.com/">old Nintendo games</a> as a kid, because last weekend I put together <a href="/lab/spacius/">Spacius! A Space Adventure</a>. My goal was to make a fun, simple game using only JavaScript that would work in any browser. That&#8217;s right folks, this game was made using just <code>div</code> elements! Really, there&#8217;s nothing hardcore in here that would require <code>canvas</code>, so I guess that shouldn&#8217;t blow any minds. But this game has been tested and works in IE6, IE7, FireFox 2/3, Opera 9.5 and Safari 3.
</p>
<p>
My one cop-out was falling back on flash for the audio, but until all browsers support HTML5 (or some <a href="http://blog.nihilogic.dk/">mad genius</a> makes a JavaScript-only audio player), this is the best I could do. Spacius! uses <a href="http://www.schillmania.com/">Scott Schiller&#8217;s</a> <em>fantastic</em> <a href="http://www.schillmania.com/projects/soundmanager2/">Sound Manager 2</a> to enable sound. There&#8217;s a little latency, but it otherwise works like a charm.
</p>
<p>
<a href="/lab/spacius/"><img alt="Spacius! A Space Adventure" src="/assets/img/spacius-a-space-adventure/screenshot.gif"/></a>
</p>
<p>
One really cool thing about the way Spacius! works is that it takes the shape of its containing element. So it was really trivial to make an <a href="/lab/spacius/?width=800&amp;height=600">800&#215;600 pixel version</a>.
</p>
<p>
<strong>Here&#8217;s how to play:</strong> Press the <strong>space bar</strong> to begin the game. Use the <strong>arrow keys</strong> to move the ship. Once playing, use the <strong>space bar</strong> to shoot balls of excitement. The <strong>S</strong> key toggles sound on/off.
</p>
<p>
There are <strong>six waves</strong> in Spacius!. The last one begins at <strong>10,000 points</strong>, and it&#8217;s <em>really hard</em> so only total badasses will be able to get super high scores (yes, that&#8217;s a challenge).
</p>
<p>
Here are the <acronym title="Unidentified Flying Object">UFO</acronym> scores:
</p>
<p>
<img alt="Bomber" src="/lab/spacius/ufo_bomber.gif"/><br />
<strong>Bomber:</strong> 15 points
</p>
<p>
<img alt="Bogey" src="/lab/spacius/ufo_bogey.gif"/><br />
<strong>Bogey:</strong> 20 points
</p>
<p>
<img alt="Meteor" src="/lab/spacius/ufo_meteor.gif"/><br />
<strong>Meteor:</strong> 50 points
</p>
<p>
<img alt="Death Star" src="/lab/spacius/ufo_ds.gif"/><br />
<strong>&#8220;Death Star&#8221;:</strong> 25 points
</p>
<p>
So what&#8217;re you waiting for?? <a href="/lab/spacius/">PLAY NOW!</a></p>
]]></content:encoded>
			<wfw:commentRss>http://scriptnode.com/article/spacius-a-space-adventure/feed/</wfw:commentRss>
		<slash:comments>32</slash:comments>
		</item>
	</channel>
</rss>
