<?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>Sid Roberts &#187; JavaScript</title>
	<atom:link href="http://www.sidroberts.co.uk/category/javascript/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.sidroberts.co.uk</link>
	<description>Well, hello there! This is the site of Sid Roberts - a web developer in Leeds, England. I'm a 16-year old high school student studying Computing, Mathematics (Mechanics), Further Maths and Economics.</description>
	<lastBuildDate>Sat, 30 Jan 2010 15:49:22 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0</generator>
		<item>
		<title>Notes From A Selector Engine</title>
		<link>http://www.sidroberts.co.uk/2009/09/05/notes-from-a-selector-engine/</link>
		<comments>http://www.sidroberts.co.uk/2009/09/05/notes-from-a-selector-engine/#comments</comments>
		<pubDate>Sat, 05 Sep 2009 20:55:45 +0000</pubDate>
		<dc:creator>Sid Roberts</dc:creator>
				<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[querySelectorAll]]></category>

		<guid isPermaLink="false">http://www.sidroberts.co.uk/?p=239</guid>
		<description><![CDATA[As previously stated, I’ve recently been working on a selector engine. Unfortunately, as every browser behaves slightly differently, I’ve had to resort to constructing compatibility tables. Seeing as they can be useful in other applications, I thought I’d post it here: Element.querySelectorAll A browser-native selector engine that allows you to select element nodes based on [...]]]></description>
			<content:encoded><![CDATA[<p>As previously stated, I’ve recently been working on a selector engine. Unfortunately, as every browser behaves slightly differently, I’ve had to resort to constructing compatibility tables. Seeing as they can be useful in other applications, I thought I’d post it here:</p>
<h3><code><a href="https://developer.mozilla.org/En/DOM/Element.querySelectorAll" title="Element.querySelectorAll on Mozilla Developer Center">Element.querySelectorAll</a></code></h3>
<p>A browser-native selector engine that allows you to select element nodes based on a <acronym title="Cascading Style Sheet">CSS</acronym> selector (for example: <code>div p a</code>).</p>
<pre><code>var a = document.getElementById('a');

a.querySelectorAll('div.post > p a[class]');</code></pre>
<table>
<tr>
<th>IE6</th>
<th>IE7</th>
<th>IE8</th>
<th>Firefox 3</th>
<th>Firefox 3.5</th>
<th>Opera 9</th>
<th>Opera 10</th>
<th>Safari 3</th>
<th>Safari 4</th>
<th>Chrome 1</th>
<th>Chrome 2</th>
</tr>
<tr>
<td>no</td>
<td>no</td>
<td>no</td>
<td>no</td>
<td>yes</td>
<td>no</td>
<td>yes</td>
<td>no</td>
<td>yes</td>
<td>yes</td>
<td>yes</td>
</tr>
</table>
<h3><code><a href="https://developer.mozilla.org/En/DOM/Element.firstElementChild" title="Element.firstElementChild on Mozilla Developer Center">Element.firstElementChild</a></code> / <code><a href="https://developer.mozilla.org/En/DOM/Element.lastElementChild" title="Element.lastElementChild on Mozilla Developer Center">Element.lastElementChild</a></code> / <code><a href="https://developer.mozilla.org/En/DOM/Element.previousElementSibling" title="Element.previousElementSibling on Mozilla Developer Center">Element.previousElementSibling</a></code> / <code><a href="https://developer.mozilla.org/En/DOM/Element.nextElementSibling" title="Element.nextElementSibling on Mozilla Developer Center">Element.nextElementSibling</a></code></h3>
<p>Selects the first/last element child or the previous/next element sibling. Saves on extrenuous code like:</p>
<pre><code>var previous = document.getElementById('example');
while((previous = previous.previousSibling) !== null &#038;& previous.nodeType !== 1) { }</code></pre>
<pre><code>var a = document.getElementById('a');

a.firstElementChild;
a.lastElementChild;
a.previousElementSibling;
a.nextElementSibling;</code></pre>
<table>
<tr>
<th>IE6</th>
<th>IE7</th>
<th>IE8</th>
<th>Firefox 3</th>
<th>Firefox 3.5</th>
<th>Opera 9</th>
<th>Opera 10</th>
<th>Safari 3</th>
<th>Safari 4</th>
<th>Chrome 1</th>
<th>Chrome 2</th>
</tr>
<tr>
<td>no</td>
<td>no</td>
<td>no</td>
<td>no</td>
<td>yes</td>
<td>yes</td>
<td>yes</td>
<td>yes</td>
<td>yes</td>
<td>yes</td>
<td>yes</td>
</tr>
</table>
<h3><code><a href="https://developer.mozilla.org/En/DOM/Element.children" title="Element.children on Mozilla Developer Center">Element.children</a></code></h3>
<p>Similar to the <code>childNodes</code> method, but without text nodes and comments.</p>
<pre><code>var a = document.getElementById('a');

a.children;</code></pre>
<table>
<tr>
<th>IE6</th>
<th>IE7</th>
<th>IE8</th>
<th>Firefox 3</th>
<th>Firefox 3.5</th>
<th>Opera 9</th>
<th>Opera 10</th>
<th>Safari 3</th>
<th>Safari 4</th>
<th>Chrome 1</th>
<th>Chrome 2</th>
</tr>
<tr>
<td>almost (includes comments)</td>
<td>almost (includes comments)</td>
<td>almost (includes comments)</td>
<td>no</td>
<td>yes</td>
<td>yes</td>
<td>yes</td>
<td>yes</td>
<td>yes</td>
<td>yes</td>
<td>yes</td>
</tr>
</table>
<h3><code><a href="http://ejohn.org/blog/comparing-document-position/" title="Comparing Document Position by John Resig">Element.compareDocumentPosition</a></code></h3>
<p>Allows you to compare one node’s position to another. Returns a <a href="http://en.wikipedia.org/wiki/Mask_%28computing%29">bitmask</a>.</p>
<pre><code>var a = document.getElementById('a');
var b = document.getElementById('b');

a.compareDocumentPosition(b);</code></pre>
<table>
<tr>
<th>IE6</th>
<th>IE7</th>
<th>IE8</th>
<th>Firefox 3</th>
<th>Firefox 3.5</th>
<th>Opera 9</th>
<th>Opera 10</th>
<th>Safari 3</th>
<th>Safari 4</th>
<th>Chrome 1</th>
<th>Chrome 2</th>
</tr>
<tr>
<td>no</td>
<td>no</td>
<td>no</td>
<td>yes</td>
<td>yes</td>
<td>yes</td>
<td>yes</td>
<td>yes</td>
<td>yes</td>
<td>no</td>
<td>yes</td>
</tr>
</table>
<h3><code><a href="http://ejohn.org/blog/comparing-document-position/" title="Comparing Document Position by John Resig">Element.contains</a></code></h3>
<p>Returns a boolean whether or not an element is contained within another.</p>
<pre><code>var a = document.getElementById('a');
var b = document.getElementById('b');

a.contains(b);</code></pre>
<table>
<tr>
<th>IE6</th>
<th>IE7</th>
<th>IE8</th>
<th>Firefox 3</th>
<th>Firefox 3.5</th>
<th>Opera 9</th>
<th>Opera 10</th>
<th>Safari 3</th>
<th>Safari 4</th>
<th>Chrome 1</th>
<th>Chrome 2</th>
</tr>
<tr>
<td>yes</td>
<td>yes</td>
<td>yes</td>
<td>no</td>
<td>no</td>
<td>yes</td>
<td>yes</td>
<td>yes</td>
<td>yes</td>
<td>yes</td>
<td>yes</td>
</tr>
</table>
]]></content:encoded>
			<wfw:commentRss>http://www.sidroberts.co.uk/2009/09/05/notes-from-a-selector-engine/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Array Tidy</title>
		<link>http://www.sidroberts.co.uk/2009/07/09/array-tidy/</link>
		<comments>http://www.sidroberts.co.uk/2009/07/09/array-tidy/#comments</comments>
		<pubDate>Thu, 09 Jul 2009 14:34:55 +0000</pubDate>
		<dc:creator>Sid Roberts</dc:creator>
				<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[array]]></category>
		<category><![CDATA[prototype]]></category>

		<guid isPermaLink="false">http://www.sidroberts.co.uk/?p=219</guid>
		<description><![CDATA[I’ve been working on a selector engine recently, and given the complexity of it, it’s easier to return a multi-dimensional array than a flat one (for example: [['this'], 'is', ['an', 'example']] instead of ['this', 'is', 'an', 'example']). Of course, returning such an array to another function is a bit pointless because it requires that function [...]]]></description>
			<content:encoded><![CDATA[<p>I’ve been working on a <a href="http://www.google.co.uk/search?q=css+selector+engine" title="CSS Selector Engine in JavaScript">selector engine</a> recently, and given the complexity of it, it’s easier to return a multi-dimensional array than a flat one (for example: <code>[['this'], 'is', ['an', 'example']]</code> instead of <code>['this', 'is', 'an', 'example']</code>). Of course, returning such an array to another function is a bit pointless because it requires that function to traverse through the array in order to flatten it so it can be used efficiently. Another problem with the selector engine is that sometimes, an element can be returned twice (for example: <code>$('div, #content')</code>, where <code>#content</code> is a <code>div</code>). Because of this, I wrote a <code>tidy</code> function that flattens the array and removes duplicate indexes.</p>
<p>Unfortunately, it requires some additional code:</p>
<h3><code>indexOf</code></h3>
<p>Returns the first index where a value (<code>searchStr</code>) appears. <code>startIndex</code> allows you to begin the search at a predefined index.</p>
<pre><code>Array.prototype.indexOf = Array.prototype.indexOf || function(searchStr, startIndex) {
	for(var i = startIndex || 0, thisLength = this.length; i &lt; thisLength; i++) {
		if(searchStr === this[i]) {
			return i;
		}
	}

	return -1;
};</code></pre>
<h3><code>inArray</code></h3>
<p>Returns either <code>true</code> or <code>false</code> if a value (<code>searchStr</code>) is in an array. <code>startIndex</code> allows you to begin the search at a predefined index.</p>
<pre><code>Array.prototype.inArray = function(searchStr, startIndex) {
	return this.indexOf(searchStr, startIndex) &gt; -1;
};</code></pre>
<h3><code>flatten</code></h3>
<p>Flattens a multi-dimensional array to a one-dimensional array.</p>
<pre><code>Array.prototype.flatten = function() {
	for(var i = 0, thisLength = this.length, b = []; i &lt; thisLength; i++) {
		if(this[i].constructor === Array) {
			this[i] = this[i].flatten();

			for(var j = 0, thisILength = this[i].length; j &lt; thisILength; j++) {
				b.push(this[i][j].constructor === Array ? this[i][j].flatten() : this[i][j]);
			}
		}
		else {
			b.push(this[i]);
		}
	}

	return b;
};</code></pre>
<h3><code>tidy</code></h3>
<p>Tidies up an array by removing dupe values and flattening it to a one dimensional array.</p>
<pre><code>Array.prototype.tidy = function() {
	var a = this.flatten();
	var b = [];

	for(var i = 0, aLength = a.length; i &lt; aLength; i++) {
		if(!b.inArray(a[i])) {
			b.push(a[i]);
		}
	}

	return b;
};</code></pre>
<p>All this code has been tested on the following browsers and works perfectly:</p>
<ul>
<li>Firefox 1.5, 2, 3, 3.5</li>
<li>Chrome 1, 2, 3</li>
<li>Opera 7, 8, 9.5, 9.64, 10</li>
<li>Safari 3, 4</li>
<li>Internet Explorer 6, 7, 8</li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://www.sidroberts.co.uk/2009/07/09/array-tidy/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>JavaScript Benchmarking</title>
		<link>http://www.sidroberts.co.uk/2009/07/03/javascript-benchmarking/</link>
		<comments>http://www.sidroberts.co.uk/2009/07/03/javascript-benchmarking/#comments</comments>
		<pubDate>Fri, 03 Jul 2009 21:31:21 +0000</pubDate>
		<dc:creator>Sid Roberts</dc:creator>
				<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[benchmark]]></category>
		<category><![CDATA[optimise]]></category>

		<guid isPermaLink="false">http://www.sidroberts.co.uk/?p=209</guid>
		<description><![CDATA[I’ve been coding a few functions and methods for an upcoming project and needed to benchmark them. Firebug’s profile tool is pretty good, but it only takes into account one execution of the code — but what if that one instance was particularly slow or particularly fast? For better results, you’d have to repeat the [...]]]></description>
			<content:encoded><![CDATA[<p>I’ve been coding a few functions and methods for an upcoming project and needed to benchmark them. <a href="http://getfirebug.com/js.html">Firebug’s profile tool</a> is pretty good, but it only takes into account one execution of the code — but what if that one instance was particularly slow or particularly fast? For better results, you’d have to repeat the function multiple times to get a better idea of how quick (or slow) it is. So in order to do this, I’ve built a benchmarking tool that bolts onto the <code>Function</code> Prototype:</p>
<pre><code>Function.prototype.benchmark = function(iterations) {
	if(iterations === null || isNaN(iterations) || iterations &lt; 1) { throw new TypeError(); }

	var begin = (new Date()).getTime();

	for(var i = 0; i &lt; iterations; i++) {
		this();
	}

	var end = (new Date()).getTime();

	return (end - begin) / iterations; // in milliseconds
};</code></pre>
<p>Use it like this:</p>
<pre><code>var example = function() {
	// run some code
};

var benchmark = example.benchmark(100); // run example 100 times</code></pre>
<p>In a nutshell, <code>example</code> is executed 100 times and <code>benchmark</code> contains the average time it took in milliseconds to execute it. Obviously more iterations gives a better average but could potentially crash if the number is too high. For big functions and libraries, I’d recommend starting off low (maybe 100) and then ramping it up but for small functions, you could easily start at up to 10,000 or maybe even 100,000. Make sure there isn’t any code in there that could potentially ruin the benchmarking — particularly <code>alert</code>s.</p>
<p>Remember to take into account slow machines and portable devices, as not every browser and computer will do it at the same speed.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.sidroberts.co.uk/2009/07/03/javascript-benchmarking/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Image Preloader</title>
		<link>http://www.sidroberts.co.uk/2008/07/15/image-preloader/</link>
		<comments>http://www.sidroberts.co.uk/2008/07/15/image-preloader/#comments</comments>
		<pubDate>Tue, 15 Jul 2008 17:48:48 +0000</pubDate>
		<dc:creator>Sid Roberts</dc:creator>
				<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[ajax]]></category>
		<category><![CDATA[image]]></category>

		<guid isPermaLink="false">http://www.sidroberts.co.uk/?p=47</guid>
		<description><![CDATA[With Ajax being all the rage, preloading images has become somewhat important. The problem is, loading them with all the other page components adds to the load time and it may not even be used. Enter preloadImage — a function set to stop all that. It’s very simple but can be used to powerful means: [...]]]></description>
			<content:encoded><![CDATA[<p>With Ajax being all the rage, preloading images has become somewhat important. The problem is, loading them with all the other page components adds to the load time and it may not even be used. Enter <code>preloadImage</code> — a function set to stop all that. It’s very simple but can be used to powerful means:</p>
<pre><code>var preloadImage = function(url, callback) {
	var image = new Image();
	image.src = url;
	image.onload = image.onabort = image.onerror = callback;
	return image;
};</code></pre>
<p>Just specify the <acronym title="Uniform Resource Locator">URL</acronym> (<code>url</code>) and the callback function (<code>callback</code>) as so:</p>
<pre><code>var callback = function(e) {
	alert(e.type);
};

var image = preloadImage('http://www.sidroberts.co.uk/image.gif', callback);</code></pre>
<p>On the load event, the abort event or the error event, the callback function will be executed. You can distinguish these with the <code>type</code> property which is <code>"load"</code>, <code>"abort"</code> and <code>"error"</code> respectively.</p>
<p>Now any image that points to that <acronym title="Uniform Resource Locator">URL</acronym> will load almost instantly.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.sidroberts.co.uk/2008/07/15/image-preloader/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Extending Regular Expressions</title>
		<link>http://www.sidroberts.co.uk/2008/06/28/extending-regular-expressions/</link>
		<comments>http://www.sidroberts.co.uk/2008/06/28/extending-regular-expressions/#comments</comments>
		<pubDate>Sat, 28 Jun 2008 20:47:09 +0000</pubDate>
		<dc:creator>Sid Roberts</dc:creator>
				<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[regular expressions]]></category>

		<guid isPermaLink="false">http://www.sidroberts.co.uk/?p=41</guid>
		<description><![CDATA[You know the problem with regular expressions in JavaScript?: There’s not enough to do. Sure, you can use its methods against strings but there’s nothing that allows you to manipulate the actual expressions. Where is the property for all the modifiers? How can you add or remove a modifier? The simple answer is that it [...]]]></description>
			<content:encoded><![CDATA[<p>You know the problem with regular expressions in JavaScript?: There’s not enough to do. Sure, you can use its methods against strings but there’s nothing that allows you to manipulate the actual expressions. Where is the property for all the modifiers? How can you add or remove a modifier? The simple answer is that it isn’t possible. The long and complicated way says that it is. The only problem is that the code is a little bit ugly:</p>
<pre><code>RegExp.prototype.modifiers = function() {
	return /^\/(.+)\/([gim]+?)$/i.exec(this.toString())[2].split('');
};</code></pre>
<p>Don’t say I didn’t warn you.</p>
<p>In short, that method converts the expression to a string and then executes another regular expression with it. This new regular expression takes away the main pattern and leaves the modifiers in a string. That string is then split into individual characters so you have an array of them (for example: <code>['g', 'i']</code>).</p>
<p>This magic regular expression can also be used for extracting a pattern, which, in turn, allows you to rebuild it with the <code>RegExp</code> constructor — modifiers included. This is the method for extracting the pattern:</p>
<pre><code>RegExp.prototype.pattern = function() {
	return /^\/(.+)\/([gim]+?)$/i.exec(this.toString())[1];
};</code></pre>
<p>Rebuilding it is as simple as this:</p>
<pre><code>var original = /\s+/g;

var pattern = original.pattern();
var modifiers = original.modifiers().join('');

var better = new RegExp(pattern, modifiers);</code></pre>
<p>So, putting two and two together, if we can extract the pattern and the modifiers, and rebuild it, what’s stopping us from changing it along the way? Enter <code>addModifiers</code> and <code>removeModifiers</code>:</p>
<pre><code>RegExp.prototype.addModifiers = function(modifiers) {
	return new RegExp(this.pattern(), this.modifiers().join('') + modifiers.join(''));
};

RegExp.prototype.removeModifiers = function(modifiers) {
	return new RegExp(this.pattern(), this.modifiers().join('').replace(new RegExp(modifiers.join('|'), 'i'), ''));
};</code></pre>
<p>With the <code>addModifiers</code> method, you may have noticed that I haven’t bothered to check for the existing modifiers. This is because you can duplicate a modifier on a regular expression and it won’t matter as it’ll only be counted once. Both of these methods allow multiple modifiers and require them to be an array (<code>['g', 'i']</code>):</p>
<pre><code>var original = /\s+/g;

original = original.addModifiers(['i']); // /\s+/gi
original = original.removeModifiers(['g']); // /\s+/i

pattern = original.pattern(); // '\s+'
modifiers = original.modifiers(); ['i']</code></pre>
]]></content:encoded>
			<wfw:commentRss>http://www.sidroberts.co.uk/2008/06/28/extending-regular-expressions/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>getElementsByAttribute</title>
		<link>http://www.sidroberts.co.uk/2008/06/21/getelementsbyattribute/</link>
		<comments>http://www.sidroberts.co.uk/2008/06/21/getelementsbyattribute/#comments</comments>
		<pubDate>Sat, 21 Jun 2008 10:52:19 +0000</pubDate>
		<dc:creator>Sid Roberts</dc:creator>
				<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[DOM]]></category>
		<category><![CDATA[getelementsbyattribute]]></category>

		<guid isPermaLink="false">http://www.sidroberts.co.uk/?p=37</guid>
		<description><![CDATA[I wanted to extend getElementsByAttribute to search a specific attribute and whilst some getElementsByAttribute functions exist, none of them feel that fantastic. Object.prototype.getElementsByAttribute = document.getElementsByAttribute = document.getElementsByAttribute &#124;&#124; function(attribute, value) { switch(attribute) { case 'id': return [this.getElementById(value)]; case 'tagName': return this.getElementsByTagName(value); } for(var i = 0, elements = this.getElementsByTagName('*'), elementsLength = elements.length, b = []; [...]]]></description>
			<content:encoded><![CDATA[<p>I wanted to extend <a href="http://www.sidroberts.co.uk/2008/06/06/getelementsbyclassname/"><code>getElementsByAttribute</code></a> to search a specific attribute and whilst some <code>getElementsByAttribute</code> functions exist, none of them feel that fantastic.</p>
<pre><code>Object.prototype.getElementsByAttribute = document.getElementsByAttribute = document.getElementsByAttribute || function(attribute, value) {
	switch(attribute) {
		case 'id':
			return [this.getElementById(value)];
		case 'tagName':
			return this.getElementsByTagName(value);
	}

	for(var i = 0, elements = this.getElementsByTagName('*'), elementsLength = elements.length, b = []; i &lt; elementsLength; i++)
	{
		if(elements[i][attribute] == value)
		{
			b.push(elements[i]);
		}
	}

	return b;
};</code></pre>
<p>First of all, if you can, optimise. That’s why there’s a <code>switch</code> statement that checks for <code>"tagName"</code> and <code>"id"</code> in the cases that you would want to use <code>getElementsByTagName</code> or <code>getElementById</code>. I made the <code>getElementById</code> return in an array so every result from <code>getElementsByAttribute</code> was an array but you may want to change this. If you have a <code>getElementsByClassName</code> function, you could also incorporate it into the <code>switch</code> statement.</p>
<p>Very simply, it runs through an array of all the child elements and adds it to an array if it matches the criteria. That array is then returned.</p>
<p>And because of how it is designed, you can call it with any <acronym title="Document Object Model">DOM</acronym> element:</p>
<pre><code>document.getElementsByAttribute('title', 'Document Object Model');

var content = document.getElementById('content);
content.getElementsByAttribute('title', 'Document Object Model');</code></pre>
]]></content:encoded>
			<wfw:commentRss>http://www.sidroberts.co.uk/2008/06/21/getelementsbyattribute/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Don’t Repeat Yourself</title>
		<link>http://www.sidroberts.co.uk/2008/06/13/dont-repeat-yourself/</link>
		<comments>http://www.sidroberts.co.uk/2008/06/13/dont-repeat-yourself/#comments</comments>
		<pubDate>Fri, 13 Jun 2008 19:27:51 +0000</pubDate>
		<dc:creator>Sid Roberts</dc:creator>
				<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[dry]]></category>

		<guid isPermaLink="false">http://www.sidroberts.co.uk/?p=33</guid>
		<description><![CDATA[The DRY philosophy is basically about not repeating code when you don’t need to. This isn’t necessarily about shortening functions like getElementById but rather stopping that bad habit where you have two functions that do almost the same job. In return, you get code that is not only smaller in file size but also easier [...]]]></description>
			<content:encoded><![CDATA[<p>The <acronym title="Don't Repeat Yourself">DRY</acronym> philosophy is basically about not repeating code when you don’t need to. This isn’t necessarily about <a href="http://www.sidroberts.co.uk/2008/06/06/shortening-documentgetelementbyid/">shortening functions like <code>getElementById</code></a> but rather stopping that bad habit where you have two functions that do almost the same job. In return, you get code that is not only smaller in file size but also easier to manage.</p>
<p>Take this as an example:</p>
<pre><code>var getAcontent = function() {
	return document.getElementById('a').innerHTML;
};

var getBcontent = function() {
	return document.getElementById('b').innerHTML;
};</code></pre>
<p>So ignoring that these <abbr title="Identification">ID</abbr>s aren’t semantic, these two functions do exactly the same thing, just on different elements — defined as string variables. Why do you need two functions for this? What will you do when you need to get another element’s contents? By specifying the <abbr title="Identification">ID</abbr> as an argument, you can get the contents of any element:</p>
<pre><code>var getContent = function(id) {
	return document.getElementById(id).innerHTML;
};</code></pre>
<p>This function is not only half the size of the other two functions but it also opens up much more capabilities. By making functions generic, you can keep them <acronym title="Don't Repeat Yourself">DRY</acronym>.</p>
<p>Another tip is to look at your code and see if you have any strings hard-coded in your functions. Remove them and replace them with arguments, if possible. Some of them will have valid reasons for being there and to use the <code>getContent</code> function, a string will need to be hard-coded in most circumstances.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.sidroberts.co.uk/2008/06/13/dont-repeat-yourself/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>getElementsByClassName</title>
		<link>http://www.sidroberts.co.uk/2008/06/06/getelementsbyclassname/</link>
		<comments>http://www.sidroberts.co.uk/2008/06/06/getelementsbyclassname/#comments</comments>
		<pubDate>Fri, 06 Jun 2008 21:26:14 +0000</pubDate>
		<dc:creator>Sid Roberts</dc:creator>
				<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[DOM]]></category>
		<category><![CDATA[getelementsbyclassname]]></category>

		<guid isPermaLink="false">http://www.sidroberts.co.uk/?p=32</guid>
		<description><![CDATA[Seeing as Firefox 3, Safari 3.1 and Opera 9.5b now support getElementsByClassName, it only seems fair to add support for older browsers, thus enabling proper use of it. Object.prototype.getElementsByClassName = document.getElementsByClassName = document.getElementsByClassName &#124;&#124; function(className) { className = className.replace(/\s+/g, ' ').replace(/^\s&#124;![A-Za-z0-9-_\s]&#124;\s$/g, '').split(' '); for (var i = 0, elements = this.getElementsByTagName('*'), elementsLength = elements.length, b [...]]]></description>
			<content:encoded><![CDATA[<p>Seeing as <a href="http://releases.mozilla.org/pub/mozilla.org/firefox/releases/3.0b1/">Firefox 3</a>, <a href="http://www.apple.com/safari/download/">Safari 3.1</a> and <a href="http://www.opera.com/download/index.dml?ver=9.50b">Opera 9.5b</a> now support <code>getElementsByClassName</code>, it only seems fair to add support for older browsers, thus enabling proper use of it.</p>
<pre><code>Object.prototype.getElementsByClassName = document.getElementsByClassName = document.getElementsByClassName || function(className) {
	className = className.replace(/\s+/g, ' ').replace(/^\s|![A-Za-z0-9-_\s]|\s$/g, '').split(' ');

	for (var i = 0, elements = this.getElementsByTagName('*'), elementsLength = elements.length, b = [], classNameLength = className.length, passed = true; i &lt; elementsLength; i++, passed = true) {
		for (var j = 0; j &lt; classNameLength &amp;&amp; passed; j++) {
			passed = (new RegExp('(^|\\\s)' + className[j] + '(\\\s|$)', 'i')).test(elements[i].className);
		}

		if (passed) {
			b.push(elements[i]);
		}
	}

	return b;
};</code></pre>
<p><code>document.getElementsByClassName</code> works in the 30+ browsers that I’ve tested, apart from Internet Explorer 5.5 or below and Dillo 0.8.6. I’d change it but, to be honest, nobody uses Internet Explorer 5.5 or below anyway and Dillo hasn’t been updated in 2 years.</p>
<p>Something like <code>document.getElementById('content').getElementsByClassName</code> doesn’t work in all browsers, notably Internet Explorer 6 and 7 (see <a href="#comment-45">comment by Michael</a> and <a href="#comment-46">comment by Sid</a>).</p>
<p>I should also note that it follows the <a title="Mozilla specification for getElementsByClassName" href="http://developer.mozilla.org/en/docs/DOM:document.getElementsByClassName">Mozilla <abbr title="specifications">spec</abbr></a> to the letter — meaning that <code>document.getElementsByClassName('classOne classTwo');</code> will return any element with class names of <strong>both</strong> <code>classOne</code> and <code>classTwo</code>. Of course, this function degrades rather nicely with newer browsers or where a <code>getElementsByClassName</code> function has already been defined so by following the <abbr title="specification">spec</abbr>, you should get on pretty fine.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.sidroberts.co.uk/2008/06/06/getelementsbyclassname/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Shortening document.getElementById</title>
		<link>http://www.sidroberts.co.uk/2008/06/06/shortening-documentgetelementbyid/</link>
		<comments>http://www.sidroberts.co.uk/2008/06/06/shortening-documentgetelementbyid/#comments</comments>
		<pubDate>Fri, 06 Jun 2008 09:25:49 +0000</pubDate>
		<dc:creator>Sid Roberts</dc:creator>
				<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[DOM]]></category>
		<category><![CDATA[getelementbyid]]></category>

		<guid isPermaLink="false">http://www.sidroberts.co.uk/?p=34</guid>
		<description><![CDATA[It’s not a terrible crime, or even a crime at all but by continually using document.getElementById, things can get a little repetitive. There are several ways with varying depth to shorten it, all relying on how much work you want to do or how often you’ll use it. Possibly the most easiest method is to [...]]]></description>
			<content:encoded><![CDATA[<p>It’s not a terrible crime, or even a crime at all but by continually using <code>document.getElementById</code>, things can get a little repetitive. There are several ways with varying depth to shorten it, all relying on how much work you want to do or how often you’ll use it.</p>
<p>Possibly the most easiest method is to use a <a href="http://en.wikipedia.org/wiki/List_of_JavaScript_libraries#JavaScript">JavaScript library</a> but they can add notably to your bandwidth — especially if you’re just using it to shorten <code>document.getElementById</code>.</p>
<p>You could just map a short name to it:</p>
<pre><code>var $ = document.getElementById;

var example = $('content');</code></pre>
<p>Put simply, just use the <code>$</code> function instead and it’ll work exactly the same.</p>
<p>Or if you want to make it easy to get several elements at once, try the modified <a href="http://www.prototypejs.org/api/utility/dollar">Prototype $ method</a>:</p>
<pre><code>var $ = function() {
	for(var i = 0, argLength = arguments.length; i &lt; argLength; i++)
	{
		arguments[i] = document.getElementById(arguments[i]);
	}

	return arguments;
};

var example = $('header', 'content', 'footer'); // Returns #header, #content and #footer in an array.</code></pre>
<p>If you’ll be using the <acronym title="Document Object Model">DOM</acronym> a lot, though, it might be a good idea to write a small selector engine:</p>
<pre><code>var $ = function(selector) {
	selector = selector.replace(/\s+/g, ' ').replace(/,\s?,|\s?,\s?/g, ',').replace(/^\s|\s$/g, '').split(',');
	var b = [];

	for(var i = 0, sLength = selector.length; i &lt; sLength; i++)
	{
		var id = /^#([A-Za-z0-9-_]+)$/.exec(selector[i]);
		var tagName = /^([A-Za-z0-9-_]+)$/.exec(selector[i]);

		if(id)
		{
			selector[i] = [document.getElementById(id[1])];
		}
		else if(tagName)
		{
			selector[i] = document.getElementsByTagName(tagName[1]);
		}

		for (var j = 0, siLength = selector[i].length; j &lt; siLength; j++)
		{
			b.push(selector[i][j]);
		}
	}

return b;
};

var example = $('#header, #content, #footer, span');</code></pre>
<p>It’s not fantastic by any means but it’s a start and supports for <abbr title="Identification">ID</abbr>s and tag names.</p>
<p>As a side note, <a href="http://webbugtrack.blogspot.com/2007/08/bug-152-getelementbyid-returns.html">Internet Explorer and Opera suffer from a <code>getElementById</code> bug</a> so it may be wise to check this out before you fit all your projects with this.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.sidroberts.co.uk/2008/06/06/shortening-documentgetelementbyid/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Introducing ColourJS</title>
		<link>http://www.sidroberts.co.uk/2008/04/05/introducing-colourjs/</link>
		<comments>http://www.sidroberts.co.uk/2008/04/05/introducing-colourjs/#comments</comments>
		<pubDate>Sat, 05 Apr 2008 10:11:28 +0000</pubDate>
		<dc:creator>Sid Roberts</dc:creator>
				<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[Projects]]></category>
		<category><![CDATA[color]]></category>
		<category><![CDATA[colorjs]]></category>
		<category><![CDATA[colour]]></category>
		<category><![CDATA[colourjs]]></category>
		<category><![CDATA[CSS]]></category>
		<category><![CDATA[hexadecimal]]></category>
		<category><![CDATA[rgb]]></category>

		<guid isPermaLink="false">http://www.sidroberts.co.uk/?p=15</guid>
		<description><![CDATA[ColourJS is a JavaScript library that can take a colour and manipulate it — invert it or just change the format. Just A Few Examples ColourJS('#FF0000').invert().toHex(); // #00FFFF ColourJS('#FF0000').invert().toRGB(); // rgb(0, 255, 255) ColourJS('rgb(255, 0, 0)').invert().toRGB(); // rgb(0, 255, 255) ColourJS('rgb(100%, 0%, 20%)').invert().toRGB(); // rgb(0, 255, 204) The syntax is still a little awkward and [...]]]></description>
			<content:encoded><![CDATA[<p>ColourJS is a JavaScript library that can take a colour and manipulate it — invert it or just change the format.</p>
<h3>Just A Few Examples</h3>
<pre><code>ColourJS('#FF0000').invert().toHex(); // #00FFFF
ColourJS('#FF0000').invert().toRGB(); // rgb(0, 255, 255)

ColourJS('rgb(255, 0, 0)').invert().toRGB(); // rgb(0, 255, 255)
ColourJS('rgb(100%, 0%, 20%)').invert().toRGB(); // rgb(0, 255, 204)</code></pre>
<p>The syntax is still a little awkward and functions are minimal but for a first release, it works.</p>
<p>Licensed under <a href="http://www.gnu.org/copyleft/gpl.html">GNU <acronym title="General Public License">GPL</acronym> <abbr title="version">v</abbr>3</a>.</p>
<p><a href="/wp-content/projects/colourjs/colourjs-1.0.js">Download ColourJS 1.0 here</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.sidroberts.co.uk/2008/04/05/introducing-colourjs/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>JavaScript Port Of PHP’s is_int() And is_integer()</title>
		<link>http://www.sidroberts.co.uk/2008/03/12/javascript-port-of-phps-is_int-and-is_integer/</link>
		<comments>http://www.sidroberts.co.uk/2008/03/12/javascript-port-of-phps-is_int-and-is_integer/#comments</comments>
		<pubDate>Wed, 12 Mar 2008 16:14:47 +0000</pubDate>
		<dc:creator>Sid Roberts</dc:creator>
				<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[is_int]]></category>
		<category><![CDATA[is_integer]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[php ports]]></category>
		<category><![CDATA[variable handling]]></category>

		<guid isPermaLink="false">http://www.sidroberts.co.uk/2008/03/12/javascript-port-of-phps-is_int-and-is_integer/</guid>
		<description><![CDATA[The is_int() function finds whether the type of the given variable is integer. The two things we need to do is check that the variable’s constructor is Number and that, if we round it up, the number will still be the same. function is_int(variable) { return variable.constructor === Number &#38;&#38; Math.round(variable, 0) === variable; } [...]]]></description>
			<content:encoded><![CDATA[<p>The <code>is_int()</code> function finds whether the type of the given variable is integer. The two things we need to do is check that the <code>variable</code>’s constructor is <code>Number</code> and that, if we round it up, the number will still be the same.</p>
<pre><code>function is_int(variable)
{
	return variable.constructor === Number &amp;&amp; Math.round(variable, 0) === variable;
}</code></pre>
<p>Of course, <a href="http://www.php.net/is_integer">is_integer()</a> is just an alias so it’d be silly to not include it:</p>
<pre><code>var is_integer = is_int;</code></pre>
]]></content:encoded>
			<wfw:commentRss>http://www.sidroberts.co.uk/2008/03/12/javascript-port-of-phps-is_int-and-is_integer/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>JavaScript Port Of PHP’s end()</title>
		<link>http://www.sidroberts.co.uk/2008/03/11/javascript-port-of-phps-end/</link>
		<comments>http://www.sidroberts.co.uk/2008/03/11/javascript-port-of-phps-end/#comments</comments>
		<pubDate>Tue, 11 Mar 2008 22:19:17 +0000</pubDate>
		<dc:creator>Sid Roberts</dc:creator>
				<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[array]]></category>
		<category><![CDATA[end]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[php ports]]></category>

		<guid isPermaLink="false">http://www.sidroberts.co.uk/2008/03/11/javascript-port-of-phps-end/</guid>
		<description><![CDATA[mixed end ( array &#38;$array ) end() advances array’s internal pointer to the last element, and returns its value. End() is much more easier than the in_array() port or probably any PHP port because we’re just returning the last value: function end(array) { return array[array.length - 1]; }]]></description>
			<content:encoded><![CDATA[<pre><code>mixed <a href="http://www.php.net/end">end</a> ( array &amp;$array )</code></pre>
<blockquote cite="http://www.php.net/end"><p>end() advances <code>array</code>’s internal pointer to the last element, and returns its value.</p></blockquote>
<p>End() is much more easier than the <a href="http://www.sidroberts.co.uk/2008/03/11/javascript-port-of-phps-in_array/">in_array()  port</a> or probably any <acronym title="PHP: Hypertext Processor">PHP</acronym> port because we’re just returning the last value:</p>
<pre><code>function end(array)
{
	return array[array.length - 1];
}</code></pre>
]]></content:encoded>
			<wfw:commentRss>http://www.sidroberts.co.uk/2008/03/11/javascript-port-of-phps-end/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>JavaScript Port Of PHP’s in_array()</title>
		<link>http://www.sidroberts.co.uk/2008/03/11/javascript-port-of-phps-in_array/</link>
		<comments>http://www.sidroberts.co.uk/2008/03/11/javascript-port-of-phps-in_array/#comments</comments>
		<pubDate>Tue, 11 Mar 2008 20:42:05 +0000</pubDate>
		<dc:creator>Sid Roberts</dc:creator>
				<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[array]]></category>
		<category><![CDATA[in_array]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[php ports]]></category>

		<guid isPermaLink="false">http://www.sidroberts.co.uk/2008/03/11/javascript-port-of-phps-in_array/</guid>
		<description><![CDATA[The in_array() function searches an array (haystack) for (needle) and returns false if it is found, false otherwise. If the third parameter strict is set to true then the in_array() function will also check the types of the needle in the haystack. function in_array(needle, haystack, strict) { for(var i = 0, hLength = haystack.length, strict [...]]]></description>
			<content:encoded><![CDATA[<p>The <code>in_array()</code> function searches an array (<code>haystack</code>) for (<code>needle</code>) and returns <code>false</code> if it is found, <code>false</code> otherwise. If the third parameter <code>strict</code> is set to <code>true</code> then the <code>in_array()</code> function will also check the types of the <code>needle</code> in the <code>haystack</code>.</p>
<pre><code>function in_array(needle, haystack, strict)
{
	for(var i = 0, hLength = haystack.length, strict = !!strict; i &lt; hLength; i++)
	{
		if((!strict &amp;&amp; needle == haystack[i]) || (strict &amp;&amp; needle === haystack[i]))
		{
			return true;
		}
	}

	return false;
}</code></pre>
<p>It’s really simple and even converts <code>strict</code> to boolean if it isn’t already (<code>strict = !!strict</code>).</p>
]]></content:encoded>
			<wfw:commentRss>http://www.sidroberts.co.uk/2008/03/11/javascript-port-of-phps-in_array/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
