<?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; tutorials</title>
	<atom:link href="http://scriptnode.com/tag/tutorials/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>Making @Twitter Names Clickable</title>
		<link>http://scriptnode.com/article/making-twitter-names-clickable/</link>
		<comments>http://scriptnode.com/article/making-twitter-names-clickable/#comments</comments>
		<pubDate>Mon, 31 Aug 2009 07:10:32 +0000</pubDate>
		<dc:creator>Matt Hackett</dc:creator>
				<category><![CDATA[Novice]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[php]]></category>
		<category><![CDATA[regex]]></category>
		<category><![CDATA[script-sunday]]></category>
		<category><![CDATA[tutorials]]></category>

		<guid isPermaLink="false">http://scriptnode.com/?p=334</guid>
		<description><![CDATA[
Here&#8217;s a super quick Script Sunday for you: making @Twitter usernames clickable. Here&#8217;s an example:


@scriptnode

Should be:

@&#60;href="http://twitter.com/scriptnode"&#62;scriptnode&#60;/a&#62;

Which looks like:

@scriptnode


And here&#8217;s how to do it in PHP and JavaScript:

PHP

$text = preg_replace(&#8217;#@([a-z0-9_]+)#i&#8217;, &#8216;@&#60;a href=&#8221;http://twitter.com/\\1&#8243;&#62;\\1&#60;/a&#62;&#8217;, $text);


That was easy! Now let&#8217;s get to the more interesting JavaScript, which allows us to test inline!

JavaScript

text = text.replace(/@([a-z0-9_]+)/gi, &#8216;@&#60;a href=&#8221;http://twitter.com/$1&#8243;&#62;$1&#60;/a&#62;&#8217;);


You can run this [...]]]></description>
			<content:encoded><![CDATA[<p>
Here&#8217;s a super quick Script Sunday for you: making @Twitter usernames clickable. Here&#8217;s an example:
</p>
<p>
<code>@scriptnode</code>
</p>
<p>Should be:</p>
<p>
<code>@&lt;href="http://twitter.com/scriptnode"&gt;scriptnode&lt;/a&gt;</code>
</p>
<p>Which looks like:</p>
<p>
@<a href="http://twitter.com/scriptnode">scriptnode</a>
</p>
<p>
And here&#8217;s how to do it in PHP and JavaScript:
</p>
<h3>PHP</h3>
<p><textarea class="php" cols="50" name="code" rows="10"><br />
$text = preg_replace(&#8217;#@([a-z0-9_]+)#i&#8217;, &#8216;@&lt;a href=&#8221;http://twitter.com/\\1&#8243;&gt;\\1&lt;/a&gt;&#8217;, $text);<br />
</textarea></p>
<p>
That was easy! Now let&#8217;s get to the more interesting JavaScript, which allows us to test inline!
</p>
<h3>JavaScript</h3>
<p><textarea class="javascript" cols="50" name="code" rows="10"><br />
text = text.replace(/@([a-z0-9_]+)/gi, &#8216;@&lt;a href=&#8221;http://twitter.com/$1&#8243;&gt;$1&lt;/a&gt;&#8217;);<br />
</textarea></p>
<p>
You can run this code right here:
</p>
<div class="section">
<p id="example-twitter-output">Some @<a href="http://twitter.com/test">test</a> code</p>
<input id="example-twitter-input" type="text" value="Some @test code">
</div>
<p>
<button onclick="YAHOO.twitterExample();">Format</button>
</p>
<p><script type="text/javascript">
<!--//
YAHOO.twitterExample = function() {
var text = document.getElementById('example-twitter-input').value;
text = text.replace(/@([a-z0-9_]+)/gi, '@<a href="http://twitter.com/$1">$1</a>');
document.getElementById('example-twitter-output').innerHTML = text;
};
//-->
</script></p>
<p>
I&#8217;m awful at regular expressions; please do let me know if I could optimize somewhere or if I missed something.<br />
<strong>Edit:</strong> <code>+</code> instead of <code>*</code></p>
]]></content:encoded>
			<wfw:commentRss>http://scriptnode.com/article/making-twitter-names-clickable/feed/</wfw:commentRss>
		<slash:comments>2</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>A Seemingly Snappier User Interface</title>
		<link>http://scriptnode.com/article/a-seemingly-snappier-user-interface/</link>
		<comments>http://scriptnode.com/article/a-seemingly-snappier-user-interface/#comments</comments>
		<pubDate>Wed, 14 Jan 2009 04:55:20 +0000</pubDate>
		<dc:creator>Matt Hackett</dc:creator>
				<category><![CDATA[Advanced]]></category>
		<category><![CDATA[events]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[jquery]]></category>
		<category><![CDATA[optimization]]></category>
		<category><![CDATA[tutorials]]></category>

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

Say you&#8217;ve got a fancy user interface. You&#8217;re leveraging AJAX well, you&#8217;re making good use of best practices, and you&#8217;ve got fast servers that respond quickly.
But your user actions still aren&#8217;t quite as fast as you&#8217;d like. What else can you do?


If you&#8217;ve done things correctly, you&#8217;ve got a user interface that reacts positively to [...]]]></description>
			<content:encoded><![CDATA[<p><script src="http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js" type="text/javascript"></script></p>
<p>
Say you&#8217;ve got a fancy user interface. You&#8217;re leveraging <a href="http://ajaxian.com">AJAX</a> well, you&#8217;re making good use of <a href="http://yuiblog.com/">best practices</a>, and you&#8217;ve got fast servers that <a href="/tag/optimization/">respond quickly</a>.<br />
But your user actions still aren&#8217;t quite as fast as you&#8217;d like. What else can you do?
</p>
<p>
If you&#8217;ve done things correctly, you&#8217;ve got a user interface that reacts positively to successful flows, but will also handle errors gracefully.<br />
Even though you&#8217;re &#8220;doing it right,&#8221; consider restructuring your application: <strong>assume success</strong>. Normally, your server is up and running and operations<br />
will be completely successfully. The edge case (hopefully) is the error case. Assuming this, we can create a slightly faster user interface.
</p>
<p>
Let&#8217;s begin with a basic voting mechanism. You&#8217;ve got a control on your page that lets a user vote on an object, and a small bit of text to represent the state of said control.<br />
It may look something like this:
</p>
<div class="section">
	<button>Vote</button><br />
	<span>You haven&#8217;t voted yet</span>
</div>
<p>
This example is meant to be easy and functional; hopefully <strong>your</strong> controls are prettier.<br />
Regardless, here&#8217;s a common flow for this request and its callback states:
</p>
<ol>
<li>Listen for the <code>click</code> event on the control.</li>
<li>Send the request.</li>
<li>Display a <a href="http://ajaxload.info/">&#8220;loading&#8221; message or a typical spinner image</a>.
<li>If the call comes back successfully, provide &#8220;success&#8221; feedback to the user and update the control.</li>
<li>If the call throws an error, provide an error message.</li>
</ol>
<p>
This flow is <strong>extremely</strong> common in today&#8217;s web. But we want something more immediately responsive, so let&#8217;s restructure the flow:
</p>
<ol>
<li>
		Use <code>onmousedown</code> because it will fire off just slightly sooner than <code>onclick</code> would.<br />
		(This might not suit all user interfaces but in this case it&#8217;s fine, and it wins us a few milliseconds.)
	</li>
<li>Provide &#8220;success&#8221; feedback to the user and update the control.</li>
<li>Send the request.</li>
<li>If the call throws an error, reset the controls and provide an error message.</li>
</ol>
<p>
This structure might seem a little off. Indeed, the error case even &#8220;lies&#8221; to the user for a few milliseconds if the request fails.<br />
But it covers all of its bases; none of the previous flow is omitted.<br />
Keep in mind that <strong>the error case is the edge case</strong>, and a very large majority of the time it&#8217;s fine to assume success at first.
</p>
<p>
Using <a href="http://jquery.com/">jQuery</a>, here&#8217;s what the code might look like:
</p>
<p><textarea class="javascript" cols="10" name="code" rows="10"><br />
// Attach the mousedown event listener<br />
$(&#8217;#snappier-1-btn&#8217;).mousedown(function(e) {</p>
<p>	var el = $(this);</p>
<p>	// Go ahead and assume things went smoothly<br />
	el.attr(&#8217;disabled&#8217;, true);<br />
	el.next().html(&#8217;Voted!&#8217;);</p>
<p>	// Send the XHR<br />
	$.ajax({<br />
		error : function() {</p>
<p>			// Undo the success message and allow the user to repeat<br />
			el.attr(&#8217;disabled&#8217;, false);<br />
			el.next().html(&#8221;You haven&#8217;t voted yet&#8221;);</p>
<p>			// Let the user know what happened<br />
			alert(&#8221;Sorry, an error occurred! Please try again.&#8221;);</p>
<p>		},<br />
		type : &#8216;GET&#8217;,<br />
		url : &#8216;/feed/&#8217;<br />
	});</p>
<p>});<br />
</textarea></p>
<p>
And here&#8217;s this flow working right here on the page:
</p>
<div class="section">
	<button id="snappier-1-btn">Vote</button><br />
	<span id="snappier-1-msg">You haven&#8217;t voted yet</span>
</div>
<p><script type="text/javascript"></p>
<p>// Attach the mousedown event listener
$('#snappier-1-btn').mousedown(function(e) {</p>
<p>	var el = $(this);</p>
<p>	// Go ahead and assume things went smoothly
	el.attr('disabled', true);
	el.next().html('Voted!');</p>
<p>	// Send the XHR
	$.ajax({
		error : function() {</p>
<p>			// Undo the success message and allow the user to repeat
			el.attr('disabled', false);
			el.next().html("You haven't voted yet");</p>
<p>			// Let the user know what happened
			alert("Sorry, an error occurred! Please try again.");</p>
<p>		},
		type : 'GET',
		url : '/feed/'
	});</p>
<p>});</p>
<p></script></p>
]]></content:encoded>
			<wfw:commentRss>http://scriptnode.com/article/a-seemingly-snappier-user-interface/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Common PHP Equivalents in JavaScript</title>
		<link>http://scriptnode.com/article/common-php-equivalents-in-javascript/</link>
		<comments>http://scriptnode.com/article/common-php-equivalents-in-javascript/#comments</comments>
		<pubDate>Sat, 03 Jan 2009 09:04:45 +0000</pubDate>
		<dc:creator>Matt Hackett</dc:creator>
				<category><![CDATA[Intermediate]]></category>
		<category><![CDATA[code-style]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[php]]></category>
		<category><![CDATA[tutorials]]></category>

		<guid isPermaLink="false">http://scriptnode.com/?p=245</guid>
		<description><![CDATA[
It&#8217;s pretty widely known in the web development industry that server-side scripting is important, and PHP is an extremely common choice. Indeed, for many programmers it&#8217;s even  their first language. It&#8217;s quite common for web devs to begin on the server, then later require some client-side interaction, at which point they must turn to [...]]]></description>
			<content:encoded><![CDATA[<p>
It&#8217;s pretty widely known in the web development industry that server-side scripting is important, and <a href="http://us3.php.net/" title="PHP Hypertext Preprocessor">PHP</a> is an extremely common choice. Indeed, for many programmers <a href="http://reidburke.com/2008/10/05/when-php-is-your-first-language/">it&#8217;s even  their first language</a>. It&#8217;s quite common for web devs to begin on the server, then later require some client-side interaction, at which point they must turn to <a href="/tag/javascript/">JavaScript</a>.
</p>
<p>
I often see questions similar to, &#8220;I&#8217;ve got these few lines of PHP code, how would I do this in JavaScript?&#8221; I&#8217;ve actually <a href="/article/javascript-print_r-or-var_dump-equivalent/">already answered</a> a question like this, but I kept getting more questions, so I thought I&#8217;d cover many at once:
</p>
<ul>
<li><a href="#array-push">Pushing to an array</a></li>
<li><a href="#die"><code>die()</code> or <code>exit</code></a></li>
<li><a href="#include"><code>include</code> or <code>require</code></a></li>
<li><a href="#redirection">Redirection</a></li>
<li><a href="#static-classes">Static classes</a></li>
<li><a href="#strings">String manipulation</a></li>
</ul>
<h3 id="array-push">Pushing to an array</h3>
<p>
Pushing a new value to the end of an array is a common, trivial task. Here&#8217;s some PHP to accomplish this:
</p>
<p><textarea class="php" cols="50" name="code" rows="10"><br />
$my_array = array();<br />
$my_array[] = &#8216;a&#8217;;<br />
array_push($my_array, &#8216;b&#8217;);<br />
</textarea></p>
<p>
Also note this quick pointer from php.net&#8217;s <a href="http://us3.php.net/manual/en/function.array-push.php"><code>array_push()</code> documentation</a>:
</p>
<blockquote><p>If you use <code>array_push()</code> to add one element to the array it&#8217;s better to use <code>$array[] =</code> because in that way there is no overhead of calling a function.</p>
</blockquote>
<p>
This isn&#8217;t the case in JavaScript. The native <code>Array.push</code> method is most optimal:
</p>
<p><textarea class="javascript" cols="50" name="code" rows="10"><br />
var myArray = [];<br />
myArray.push(&#8217;a'); // This is the way to go<br />
myArray[myArray.length] = &#8216;b&#8217;; // This method is possible but bad<br />
</textarea></p>
<h3 id="die"><code>die()</code> or <code>exit</code></h3>
<p>
There has been much confusion regarding what JavaScript is and how it works in the browser. When looking for an equivalent to <code>exit</code>, one probably doesn&#8217;t understand that client-side JavaScript is a behavioral language that&#8217;s intended to react to events. In PHP, a script executes, stopping only when told to do so, and then it&#8217;s done. JavaScript lives and breathes on the page, reacting to the mouse being moved, keys being pressed and even time changing.
</p>
<p>
So it&#8217;s important to understand why this is not a fair equivalent, and that even asking for one shows a misunderstanding. That said, a bit of procedural JavaScript can be exited by using an anonymous function. Here&#8217;s some example PHP and then similar code in JavaScript:
</p>
<p><textarea class="php" cols="50" name="code" rows="10"><br />
if ($next_action == &#8216;exit&#8217;) {<br />
	exit;<br />
}</p>
<p>echo &#8216;Made it here!&#8217;;<br />
</textarea></p>
<p><textarea class="javascript" cols="50" name="code" rows="10"><br />
(function() {</p>
<p>	if (nextAction == &#8216;exit&#8217;) {<br />
		return;<br />
	}</p>
<p>	alert(&#8217;Made it here!&#8217;);</p>
<p>})();<br />
</textarea></p>
<p>
While the language behavior is not one-to-one, taking advantage of JavaScript&#8217;s closure already has advantages, among them being able to easily exit a function via <code>return</code>.
</p>
<h3 id="include"><code>include</code> or <code>require</code></h3>
<p>
There have been some arguments about this equivalence in JavaScript. Just like the previous example, this equivalence is not one-to-one and should be thought about in very different terms. That said, here is a quick example of including a PHP file within a PHP script:
</p>
<p><textarea class="php" cols="50" name="code" rows="10"><br />
// Nothing to it, just include the file:<br />
include(&#8217;my_file.php&#8217;);</p>
<p>// This code will only execute after my_file.php has been included:<br />
echo &#8216;File included!&#8217;;<br />
</textarea></p>
<p>
To include an external script in JavaScript, writing a method or including a library is definitely best. <a href="/article/dynamically-load-css-and-js-files/">I wrote about this once</a>, but there are libraries such as <a href="http://developer.yahoo.com/yui/" title="Yahoo! User Interface library">YUI</a> that have <a href="http://developer.yahoo.com/yui/get/">better support with more options</a>. Here&#8217;s what this would look like using YUI:
</p>
<p><textarea class="javascript" cols="50" name="code" rows="10"><br />
// Call YUI&#8217;s method<br />
var objTransaction = YAHOO.util.Get.script(&#8221;http://example.com/my_file.js&#8221;, {<br />
	// This function will only fire after my-file.js has been included:<br />
	onSuccess : function() {<br />
		alert(&#8221;File included!&#8221;);<br />
	}<br />
});<br />
</textarea></p>
<h3 id="redirection">Redirection</h3>
<p>
This one is easy and straightforward. A redirect is accomplished with <a href="http://us3.php.net/manual/en/function.header.php">PHP&#8217;s <code>header()</code> function</a>:
</p>
<p><textarea class="php" cols="50" name="code" rows="10"><br />
header(&#8217;Location: http://example.com&#8217;);<br />
exit; // Not necessary but a good practice<br />
</textarea></p>
<p>
Also very simple in JavaScript:
</p>
<p><textarea class="javascript" cols="50" name="code" rows="10"><br />
location.href = &#8216;http://example.com&#8217;;<br />
</textarea></p>
<h3 id="static-classes">Static classes</h3>
<p>
In PHP, it&#8217;s a pretty common programming pattern to use a static class for encapsulation, sort of namespacing some methods and properties. Here&#8217;s an example:
</p>
<p><textarea class="php" cols="50" name="code" rows="10"><br />
class Tools {</p>
<p>    public static function check_stuff() {<br />
        return true;<br />
    }</p>
<p>}</p>
<p>echo Tools::check_stuff();<br />
</textarea></p>
<p>
For this JavaScript equivalence, it probably makes the most sense to use an object literal:
</p>
<p><textarea class="javascript" cols="50" name="code" rows="10"><br />
Tools = {<br />
	checkStuff : function() {<br />
		return true;<br />
	}<br />
};</p>
<p>alert(Tools.checkStuff());<br />
</textarea></p>
<h3 id="strings">String manipulation</h3>
<p>
String manipulation is absolutely mandatory in most applications. Fortunately, it&#8217;s a breeze thanks to <a href="http://us3.php.net/manual/en/ref.strings.php">PHP&#8217;s fantastic string functions</a>:
</p>
<p><textarea class="php" cols="50" name="code" rows="10"><br />
// Replace portions within a string<br />
echo str_replace(&#8217;Hey&#8217;, &#8216;Hi&#8217;, &#8216;Hey there&#8217;); // outputs &#8220;Hi there&#8221;</p>
<p>// Capitalization<br />
echo strtolower(&#8217;Hey there&#8217;); // outputs &#8220;hey there&#8221;<br />
echo strtoupper(&#8217;Hey there&#8217;); // outputs &#8220;HEY THERE&#8221;</p>
<p>// Get a portion of a string<br />
echo substr(&#8217;Hey there&#8217;, 0, 2); // outputs &#8220;He&#8221;</p>
<p>// Get rid of extraneous whitespace<br />
echo trim(&#8217;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Hey there&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&#8217;); // outputs &#8220;Hey there&#8221;<br />
</textarea></p>
<p>
<a href="https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/String" title="Mozilla's String reference">Each of these</a> have perfect equivalents except for <code>trim()</code>, which we need to implement ourselves:
</p>
<p><textarea class="javascript" cols="50" name="code" rows="10"><br />
// Replace portions within a string<br />
alert(&#8217;Hey there&#8217;.replace(&#8217;Hey&#8217;, &#8216;Hi&#8217;)); // outputs &#8220;Hi there&#8221;</p>
<p>// Capitalization<br />
alert(&#8217;Hey there&#8217;.toLowerCase()); // outputs &#8220;hey there&#8221;<br />
alert(&#8217;Hey there&#8217;.toUpperCase()); // outputs &#8220;HEY THERE&#8221;</p>
<p>// Get a portion of a string<br />
alert(&#8217;Hey there&#8217;.substr(0, 2)); // outputs &#8220;He&#8221;</p>
<p>// Get rid of extraneous whitespace<br />
trim = function(txt) {<br />
	return txt.replace(/^\s+|\s+$/g, &#8221;);<br />
};</p>
<p>alert(trim(&#8217;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Hey there&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&#8217;)); // outputs &#8220;Hey there&#8221;</p>
<p></textarea></p>
<p>
Or, we can augment the <code>String</code> global so that strings will have this method natively:
</p>
<p><textarea class="javascript" cols="50" name="code" rows="10"><br />
String.prototype.trim = function() {<br />
	return this.replace(/^\s+|\s+$/g, &#8221;);<br />
};</p>
<p>// Get rid of extraneous whitespace<br />
alert(&#8217;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Hey there&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&#8217;.trim()); // outputs &#8220;Hey there&#8221;<br />
</textarea></p>
<p>
While not all of these equivalents are smooth (or even recommended), it&#8217;s typically helpful when learning a new language to have it compared to a language one is already familiar with. If you can think of any other common PHP tasks that have relatively similar equivalents in JavaScript, please let me know in the comments.</p>
]]></content:encoded>
			<wfw:commentRss>http://scriptnode.com/article/common-php-equivalents-in-javascript/feed/</wfw:commentRss>
		<slash:comments>4</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>Simple Cookie Script</title>
		<link>http://scriptnode.com/article/simple-cookie-script/</link>
		<comments>http://scriptnode.com/article/simple-cookie-script/#comments</comments>
		<pubDate>Sun, 19 Oct 2008 09:22:23 +0000</pubDate>
		<dc:creator>Matt Hackett</dc:creator>
				<category><![CDATA[Novice]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[script-sunday]]></category>
		<category><![CDATA[tutorials]]></category>

		<guid isPermaLink="false">http://scriptnode.com/?p=222</guid>
		<description><![CDATA[
I often chat with a lot of new JavaScript developers. Many of their questions are really easy and can be answered with single-line responses, such as, &#8220;How do you append to an array?&#8221;


myArray.push(thevalue);


Easy stuff. What&#8217;s unfortunate, though, is when the questions are a bit more involved, and these developers have already searched around a bit [...]]]></description>
			<content:encoded><![CDATA[<p>
I often <a href="irc://irc.freenode.org/#javascript">chat</a> with a lot of new JavaScript developers. Many of their questions are really easy and can be answered with single-line responses, such as, &#8220;How do you append to an array?&#8221;
</p>
<p><textarea class="javascript" cols="50" name="code" rows="5"><br />
myArray.push(thevalue);<br />
</textarea></p>
<p>
Easy stuff. What&#8217;s unfortunate, though, is when the questions are a bit more involved, and these developers have already searched around a bit and found lousy code to read and learn from. The problem is that there&#8217;s much ancient, <a href="http://www.w3schools.com/js/default.asp">awful JavaScript code</a> out there, and when performing simple search queries, these sites come up. My goal is to improve this process.
</p>
<p>
One common topic is that of cookies. Dealing with cookies is really basic stuff, but hey, that&#8217;s what the <a href="http://scriptnode.com/category/novice/">novice category</a> is for. So here&#8217;s a simple script to assist with managing cookies:
</p>
<p><textarea class="javascript" cols="50" name="code" rows="5"><br />
/**<br />
 * Global cookies object to manage cookies<br />
 * @return {Object} The exposed methods<br />
 * @public<br />
 */<br />
var cookies = (function() {</p>
<p>	/**<br />
	 * Gets a cookie&#8217;s value<br />
	 * @param {String} name The name of the cookie to get<br />
	 * @return {String} The cookie&#8217;s value, or false if it can&#8217;t find the cookie<br />
	 * @member cookies<br />
	 * @public<br />
	 */<br />
	var get = function(name) {</p>
<p>		var cookie = document.cookie,<br />
			end,<br />
			pre = name + &#8216;=&#8217;,<br />
			begin  = cookie.indexOf(&#8217;; &#8216; + pre);</p>
<p>		if (begin == -1) {<br />
			begin = cookie.indexOf(pre);<br />
			if (begin !== 0) return false;<br />
		} else {<br />
			begin += 2;<br />
		}</p>
<p>		end = document.cookie.indexOf(&#8217;;', begin);<br />
		if (end == -1) end = cookie.length;</p>
<p>		return decodeURIComponent(cookie.substring(begin + pre.length, end));</p>
<p>	};</p>
<p>	/**<br />
	 * Removes a cookie that has already been set<br />
	 * @param {String} name The name of the cookie to remove<br />
	 * @param {String} path The path of the cookie to remove<br />
	 * @param {String} domain The domain of the cookie to remove<br />
	 * @member cookies<br />
	 * @public<br />
	 */<br />
	var remove = function(name, path, domain) {</p>
<p>		var cookie = name + &#8216;=&#8217;;</p>
<p>		if (!get(name)) return;<br />
		if (path) cookie += &#8216;; path=&#8217; + path;<br />
		if (domain) cookie += &#8216;; domain=&#8217; + domain;<br />
		cookie += &#8216;; expires=Thu, 01-Jan-70 00:00:01 GMT&#8217;;</p>
<p>		document.cookie = cookie;</p>
<p>	};</p>
<p>	/**<br />
	 * Tells the browser to set a cookie<br />
	 * @param {String} name The name of the cookie to set<br />
	 * @param {String} value The value to set in the cookie<br />
	 * @param {String} expires The date that the cookie expires (must be a valid date string)<br />
	 * @param {String} path The path of the cookie to set<br />
	 * @param {String} domain The domain of the cookie to set<br />
	 * @param {Boolean} secure Whether to make the cookie secure or not<br />
	 * @member cookies<br />
	 * @public<br />
	 */<br />
	var set = function(name, value, expires, path, domain, secure) {</p>
<p>		var cookie = name + &#8216;=&#8217; + encodeURIComponent(value);</p>
<p>		if (expires) cookie += &#8216;; expires=&#8217; + expires.toGMTString();<br />
		if (path) cookie += &#8216;; path=&#8217; + path;<br />
		if (domain) cookie += &#8216;; domain=&#8217; + domain;<br />
		if (secure) cookie += &#8216;; secure&#8217;;</p>
<p>		document.cookie = cookie;</p>
<p>	};</p>
<p>	return {<br />
		get : get,<br />
		remove : remove,<br />
		set : set<br />
	};</p>
<p>})();<br />
</textarea></p>
<p>
You can download this script below:
</p>
<ul>
<li><a href="/assets/js/cookies/cookies.js">[Download cookies.js]</a> (2,160 bytes)</li>
<li><a href="/assets/js/cookies/cookies-min.js">[Download cookies-min.js]</a> (634 bytes; compressed)</li>
</ul>
<p>
Also, PPK has an in-depth <a href="http://www.quirksmode.org/js/cookies.html">article about cookies</a>. His code examples get the job done, but unfortunately create too many functions in the global scope (which, as we all know, <a href="http://yuiblog.com/blog/2006/06/01/global-domination/">should be avoided</a>).</p>
]]></content:encoded>
			<wfw:commentRss>http://scriptnode.com/article/simple-cookie-script/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Dynamically Load CSS and JS Files</title>
		<link>http://scriptnode.com/article/dynamically-load-css-and-js-files/</link>
		<comments>http://scriptnode.com/article/dynamically-load-css-and-js-files/#comments</comments>
		<pubDate>Sun, 28 Sep 2008 08:04:29 +0000</pubDate>
		<dc:creator>Matt Hackett</dc:creator>
				<category><![CDATA[Novice]]></category>
		<category><![CDATA[css]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[script-sunday]]></category>
		<category><![CDATA[tutorials]]></category>

		<guid isPermaLink="false">http://scriptnode.com/?p=183</guid>
		<description><![CDATA[
I hear a lot of developers asking about loading
CSS and JS files dynamically.
Surprisingly, creating script and link nodes is just like creating any other nodes.
All you have to do is create them using DOM methods and append to the head:

The Script

var loadCSS = function(file) {
	var link = document.createElement(&#8217;link&#8217;);
	link.href = file;
	link.rel = &#8217;stylesheet&#8217;;
	link.type = &#8216;text/css&#8217;;
	document.getElementsByTagName(&#8217;head&#8217;)[0].appendChild(link);
};
var loadJS [...]]]></description>
			<content:encoded><![CDATA[<p>
I hear a lot of developers asking about loading<br />
<a href="/tag/css/" title="Cascading Style Sheets">CSS</a> and <a href="/tag/javascript/" title="JavaScript">JS</a> files dynamically.<br />
Surprisingly, creating <code>script</code> and <code>link</code> nodes is just like creating any other nodes.<br />
All you have to do is create them using <a href="http://www.w3.org/DOM/" title="Document Object Model">DOM</a> methods and append to the <code>head</code>:
</p>
<h3>The Script</h3>
<p><textarea class="javascript" cols="50" name="code" rows="10"><br />
var loadCSS = function(file) {<br />
	var link = document.createElement(&#8217;link&#8217;);<br />
	link.href = file;<br />
	link.rel = &#8217;stylesheet&#8217;;<br />
	link.type = &#8216;text/css&#8217;;<br />
	document.getElementsByTagName(&#8217;head&#8217;)[0].appendChild(link);<br />
};</p>
<p>var loadJS = function(file) {<br />
	var script = document.createElement(&#8217;script&#8217;);<br />
	script.src = file;<br />
	script.type = &#8216;text/javascript&#8217;;<br />
	document.getElementsByTagName(&#8217;head&#8217;)[0].appendChild(script);<br />
};<br />
</textarea></p>
<h3>Example 1 &#8211; JavaScript</h3>
<p>
First let&#8217;s load up a JavaScript file. Here&#8217;s what the <a href="/assets/misc/dynamic-load/example-1.js">external JS file</a> looks like:
</p>
<p><textarea class="javascript" cols="50" name="code" rows="10"><br />
alert(&#8217;Loaded!&#8217;);<br />
</textarea></p>
<p>
And by using the above script, loading it is easy:
</p>
<p><textarea class="javascript" cols="50" name="code" rows="10"><br />
loadJS(&#8217;/assets/misc/dynamic-load/example-1.js&#8217;);<br />
</textarea></p>
<p>
<button id="example-dynamic-load-1">Load JS file</button>
</p>
<h3>Example 2 &#8211; CSS</h3>
<p>
Loading CSS is not much different. Here are the contents of the <a href="/assets/misc/dynamic-load/example-2.css">external CSS file</a>:
</p>
<p><textarea class="css" cols="50" name="code" rows="10"><br />
body {<br />
	border: 3px solid red;<br />
}<br />
</textarea></p>
<p>
Note that you can also use relative <acronym title="Uniform Resource Locators">URLs</acronym> or even files on another server:
</p>
<p><textarea class="javascript" cols="50" name="code" rows="10"><br />
loadCSS(&#8217;http://scriptnode.com/assets/misc/dynamic-load/example-2.css&#8217;);<br />
</textarea></p>
<p>
<button id="example-dynamic-load-2">Load CSS file</button>
</p>
<p>
This has been tested and works in all of the <a href="http://developer.yahoo.com/yui/articles/gbs/">standard browsers</a> including<br />
Firefox, Chrome, Internet Explorer, Opera and Safari.
</p>
<p><script type="text/javascript">
<!--//</p>
<p>var loadCSS = function(file) {
	var link = document.createElement('link');
	link.href = file;
	link.rel = 'stylesheet';
	link.type = 'text/css';
	document.getElementsByTagName('head')[0].appendChild(link);
};</p>
<p>var loadJS = function(file) {
	var script = document.createElement('script');
	script.src = file;
	script.type = 'text/javascript';
	document.getElementsByTagName('head')[0].appendChild(script);
};</p>
<p>YAHOO.util.Event.addListener('example-dynamic-load-1', 'click', function() {
	loadJS('/assets/misc/dynamic-load/example-1.js');
});</p>
<p>YAHOO.util.Event.addListener('example-dynamic-load-2', 'click', function() {
	loadCSS('http://scriptnode.com/assets/misc/dynamic-load/example-2.css');
});</p>
<p>//-->
</script></p>
]]></content:encoded>
			<wfw:commentRss>http://scriptnode.com/article/dynamically-load-css-and-js-files/feed/</wfw:commentRss>
		<slash:comments>8</slash:comments>
		</item>
		<item>
		<title>Evaluating Script Tags Dynamically</title>
		<link>http://scriptnode.com/article/evaluating-script-tags-dynamically/</link>
		<comments>http://scriptnode.com/article/evaluating-script-tags-dynamically/#comments</comments>
		<pubDate>Sun, 21 Sep 2008 08:00:30 +0000</pubDate>
		<dc:creator>Matt Hackett</dc:creator>
				<category><![CDATA[Advanced]]></category>
		<category><![CDATA[code-style]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[script-sunday]]></category>
		<category><![CDATA[tutorials]]></category>

		<guid isPermaLink="false">http://scriptnode.com/?p=142</guid>
		<description><![CDATA[
First, a disclaimer: dynamically evaluating scripts is not recommended! Indeed, if your application requires the usage of this script, chances are you&#8217;re doing it wrong. The separation of design and logic likely hasn&#8217;t been properly enforced if you&#8217;re using this method. It&#8217;s just an awkward use-case that should be avoided. That said, here it is&#8230;


Many [...]]]></description>
			<content:encoded><![CDATA[<p>
First, a disclaimer: <strong>dynamically evaluating scripts is not recommended!</strong> Indeed, if your application requires the usage of this script, chances are <em>you&#8217;re doing it wrong</em>. The separation of design and logic likely hasn&#8217;t been properly enforced if you&#8217;re using this method. It&#8217;s just an awkward use-case that should be avoided. That said, here it is&#8230;
</p>
<p>
Many JavaScript libraries support the evaluating of data returned via <a href="http://www.w3.org/TR/XMLHttpRequest/" title="XML Http Request">XHR</a>. Some, like <a href="http://developer.yahoo.com/yui/">YUI</a>, do not (yet). In other cases, folks have rolled their own <a href="http://en.wikipedia.org/wiki/List_of_Ajax_frameworks">&#8220;<acronym title="Asynchronous JavaScript and XML">AJAX</acronym> library&#8221;</a> but still want this behavior. The below script supports searching <acronym title="Hypertext Markup Language">HTML</acronym> for scripts and evaluating them:
</p>
<p><textarea class="javascript" cols="50" name="code" rows="10"><br />
/**<br />
 * Evaluate the passed content for &lt;script&gt; tags<br />
 * @param {String} html The string to parse<br />
 */<br />
var evalHTML = function(html) {</p>
<p>	var piece,<br />
		res = html.split(/&lt;script/);</p>
<p>	res.shift();</p>
<p>	for (var i = 0, len = res.length; i &lt; len; i++) {</p>
<p>		(piece = res[i].split(/&gt;/)).shift();</p>
<p>		try {<br />
			eval(piece.join(&#8217;>').split(&#8217;&lt;/scr&#8217; + &#8216;ipt&gt;&#8217;).shift());<br />
		} catch (e) {}</p>
<p>	}</p>
<p>};<br />
</textarea></p>
<p>You can execute some examples yourself below:</p>
<p><textarea class="javascript" cols="50" name="code" rows="10"><br />
// Example 1 &#8211; script inside of a div<br />
evalHTML(&#8217;&lt;div&gt;&lt;scr&#8217; +<br />
&#8216;ipt&gt;alert(&#8221;Hello, JavaScript!&#8221;);&lt;/scr&#8217; +<br />
&#8216;ipt&gt;&#8217;);<br />
</textarea></p>
<p>
<button id="example-eval-1">Execute example 1</button>
</p>
<p><textarea class="javascript" cols="50" name="code" rows="10"><br />
// Example 2 &#8211; script sets a global variable then displays it<br />
evalHTML(&#8217;&lt;scr&#8217; + &#8216;ipt&gt;var foo = &#8220;bar&#8221;;&lt;/scr&#8217; +&#8217;ipt&gt;&#8217; +<br />
&#8216;&lt;scr&#8217; + &#8216;ipt&gt;alert(foo);&lt;/scr&#8217; +&#8217;ipt&gt;&#8217;);<br />
</textarea></p>
<p>
<button id="example-eval-2">Execute example 2</button>
</p>
<p><script type="text/javascript">
<!--//
var evalHTML=function(html){var piece,res=html.split(/<script/);res.shift();for(var i=0,len=res.length;i<len;i++){(piece=res[i].split(/>/)).shift();try{eval(piece.join(">").split("<\/script>").shift())}catch(e){}}};</p>
<p>YAHOO.util.Event.addListener('example-eval-1', 'click', function() {
evalHTML('
<div><scr' + 
'ipt>alert("Hello, JavaScript!");</scr' +
'ipt>');
});</p>
<p>YAHOO.util.Event.addListener('example-eval-2', 'click', function() {
evalHTML('<scr' + 'ipt>var foo = "bar";</scr' +'ipt>' +
'<scr' + 'ipt>alert(foo);</scr' +'ipt>');
});</p>
<p>//-->
</script></p>
<ul class="download">
<li><a href="/assets/js/dynamic-eval/eval.js">[Download eval.js]</a> (376 bytes)</li>
<li><a href="/assets/js/dynamic-eval/eval-min.js">[Download eval-min.js]</a> (214 bytes; compressed)</li>
</ul>
<p>
<strong>Update 9/28/08:</strong> Fixed a bug thanks to <a href="http://foohack.com/">Isaac Schlueter</a> (see <a href="/article/evaluating-script-tags-dynamically/#comment-197">comments</a>).</p>
]]></content:encoded>
			<wfw:commentRss>http://scriptnode.com/article/evaluating-script-tags-dynamically/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>The &#8220;Last in a Loop&#8221; Bug</title>
		<link>http://scriptnode.com/article/the-last-in-a-loop-bug/</link>
		<comments>http://scriptnode.com/article/the-last-in-a-loop-bug/#comments</comments>
		<pubDate>Thu, 28 Aug 2008 09:46:03 +0000</pubDate>
		<dc:creator>Matt Hackett</dc:creator>
				<category><![CDATA[Intermediate]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[tutorials]]></category>

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

If you&#8217;ve had your hands in JavaScript for a while, chances are you&#8217;ve ran into this bug. You&#8217;ve got a bunch of elements you&#8217;re either adding to the
DOM or a bunch of listeners you&#8217;re attaching to elements. Either way, you keep getting the same result:
the last value in the loop. Here&#8217;s an example:


Let&#8217;s say [...]]]></description>
			<content:encoded><![CDATA[<h3>The Problem</h3>
<p>
If you&#8217;ve had your hands in JavaScript for a while, chances are you&#8217;ve ran into this bug. You&#8217;ve got a <strong>bunch of elements</strong> you&#8217;re either adding to the<br />
<acronym title="Document Object Model">DOM</acronym> or a bunch of listeners you&#8217;re attaching to elements. Either way, you keep getting the same result:<br />
<strong>the last value in the loop</strong>. Here&#8217;s an example:
</p>
<p>
Let&#8217;s say you&#8217;ve got a list of <strong>5 items</strong> and you want to listen to the <strong>click</strong> event for each.<br />
Many developers would immediately think of doing it this way:
</p>
<p><textarea class="javascript" cols="50" name="code" rows="10"><br />
var els = document.getElementById(&#8217;last-one-example-1&#8242;).getElementsByTagName(&#8217;LI&#8217;);</p>
<p>for (var i = 0; i &lt; els.length; i++) {<br />
	els[i].onclick = function() {<br />
		alert(&#8217;You clicked element #&#8217; + i);<br />
	};<br />
}<br />
</textarea></p>
<p>
You can try this example below:
</p>
<div class="section">
<ul id="last-one-example-1">
<li>Item #1 &#8211; click me!</li>
<li>Item #2 &#8211; click me!</li>
<li>Item #3 &#8211; click me!</li>
<li>Item #4 &#8211; click me!</li>
<li>Item #5 &#8211; click me!</li>
</ul>
</div>
<p><script type="text/javascript">
<!--//
(function() {</p>
<p>	var els = document.getElementById('last-one-example-1').getElementsByTagName('LI');</p>
<p>	for (var i = 0; i < els.length; i++) {
		els[i].onclick = function() {
			alert('You clicked element #' + i);
		};
	}</p>
<p>})();
//-->
</script></p>
<p>
No matter which element is clicked, the same result keeps appearing: <strong>You clicked element #5</strong>.<br />
This baffles many JavaScript programmers. So what&#8217;s going on here?
</p>
<p>
The issue here is a <strong>misunderstanding of <a href="http://www.jibbering.com/faq/faq_notes/closures.html">closure</a></strong>.<br />
In the above example, it&#8217;s assumed that the variable <code>i</code> will retain its value during the loop for that particular function call.<br />
But actually what&#8217;s happening is <strong>the click function is accessing the same <code>i</code> variable that the <code>for loop</code> accessed</strong>.<br />
So anytime <code>i</code> is checked, its value will be the same as it was when the loop finished.
</p>
<h3>A Solution</h3>
<p>
Usually what a developer wants to accomplish is a function listening to the click event that retains the value of<br />
<code>i</code> as it was during that iteration in the loop.<br />
Here&#8217;s a way to accomplish that behavior:
</p>
<p><textarea class="javascript" cols="50" name="code" rows="10"><br />
var els = document.getElementById(&#8217;last-one-example-2&#8242;).getElementsByTagName(&#8217;LI&#8217;);</p>
<p>for (var i = 0; i &lt; els.length; i++) {</p>
<p>	els[i].onclick = function(currentLoopValue) {<br />
		return function(e) {<br />
			alert(&#8217;You clicked element #&#8217; + currentLoopValue);<br />
		};<br />
	}(i);</p>
<p>}<br />
</textarea></p>
<p>
This pattern can be more than a little confusing. Let&#8217;s walk through it line-by-line, <strong>starting with line 5</strong>:
</p>
<ol>
<li value="5">
		This time we&#8217;re firing off a function immediately, allowing us to run some code within a closure to avoid <code>i</code> changing values on us.
	</li>
<li>We still want the <code>onclick</code> to be assigned a function to fire, so we return an anonymous function just like we did before.</li>
<li>We <code>alert</code> the item number just like we normally would (but this time it will work).</li>
<li>End the returned function.</li>
<li>
		End the <code>onclick</code> assignment.<br />
		This function gets fired off <strong>immediately</strong> because of the parentheses.<br />
		We pass <code>i</code> in, retaining its current loop value because of the function scope we declared on line 5.<br />
		This is probably the step that confuses developers the most.
	</li>
</ol>
<p>
Here is that example in action:
</p>
<div class="section">
<ul id="last-one-example-2">
<li>Item #1 &#8211; click me!</li>
<li>Item #2 &#8211; click me!</li>
<li>Item #3 &#8211; click me!</li>
<li>Item #4 &#8211; click me!</li>
<li>Item #5 &#8211; click me!</li>
</ul>
</div>
<p><script type="text/javascript">
<!--//
(function() {</p>
<p>	var els = document.getElementById('last-one-example-2').getElementsByTagName('LI');</p>
<p>	for (var i = 0; i < els.length; i++) {</p>
<p>		els[i].onclick = function(currentLoopValue) {
			return function(e) {
				alert('You clicked element #' + currentLoopValue);
			};
		}(i);</p>
<p>	}</p>
<p>})();
//-->
</script></p>
<p>
And it works the way you&#8217;d expect! What do you think?<br />
If you don&#8217;t quite understand the pattern, or have another method to use to solve this problem, I&#8217;d love to hear about it in the comments.</p>
]]></content:encoded>
			<wfw:commentRss>http://scriptnode.com/article/the-last-in-a-loop-bug/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Quickly Update DocumentRoot in Apache2</title>
		<link>http://scriptnode.com/article/quickly-update-documentroot-in-apache2/</link>
		<comments>http://scriptnode.com/article/quickly-update-documentroot-in-apache2/#comments</comments>
		<pubDate>Sun, 10 Aug 2008 19:33:50 +0000</pubDate>
		<dc:creator>Matt Hackett</dc:creator>
				<category><![CDATA[Intermediate]]></category>
		<category><![CDATA[apache]]></category>
		<category><![CDATA[code-style]]></category>
		<category><![CDATA[php]]></category>
		<category><![CDATA[script-sunday]]></category>
		<category><![CDATA[tutorials]]></category>

		<guid isPermaLink="false">http://scriptnode.com/?p=63</guid>
		<description><![CDATA[
For today&#8217;s Script Sunday I thought I&#8217;d take a go back in time a little and provide an old utility that I still to this day find useful.
It&#8217;s a script I wrote called ChangeLocalHost which alters the DocumentRoot in apache2. An example of its use would be:


./clh.php local-site.com/public_html/


Note: you must be root to run it


Given [...]]]></description>
			<content:encoded><![CDATA[<p>
For today&#8217;s <a href="/tag/script-sunday/">Script Sunday</a> I thought I&#8217;d take a go back in time a little and provide an old utility that I still to this day find useful.<br />
It&#8217;s a script I wrote called <code>ChangeLocalHost</code> which alters the <code>DocumentRoot</code> in <code>apache2</code>. An example of its use would be:
</p>
<p>
<code>./clh.php local-site.com/public_html/</code>
</p>
<p>
<em>Note: you must be <code>root</code> to run it</em>
</p>
<p>
Given this command, the script will change <code>DocumentRoot</code> to <strong>local-site.com/public_html/</strong> and restart <code>apache2</code>.<br />
I work on <a href="http://dirtybeta.com/">a lot</a> of <a href="http://valadria.com/">websites</a> (developing most of them on my laptop running <code>apache2</code>)<br />
so I use this script constantly.
</p>
<p>
Here&#8217;s the code:
</p>
<p><textarea class="javascript" cols="50" name="code" rows="10"><br />
#!/usr/bin/php<br />
&lt;?php</p>
<p>/*<br />
ChangeLocalHost v0.1 &#8211; last updated Mar 07 2007<br />
Must be root to execute. Alters the DocumentRoot in Apache2&#8217;s conf file, then restarts Apache2.<br />
*/</p>
<p>$obj_clh = new ChangeLocalHost(&#8217;/etc/apache2/sites-available/&#8217;, &#8216;default&#8217;, &#8216;/home/www/&#8217;);</p>
<p>$obj_clh-&gt;setArgs($_SERVER['argv']);<br />
$obj_clh-&gt;run();</p>
<p>/**<br />
 * CLH class constructor<br />
 * @constructor<br />
 */<br />
class ChangeLocalHost {</p>
<p>	private $arr_args,<br />
			$bit_msgs,<br />
			$str_dir,<br />
			$str_file,<br />
			$str_pre;</p>
<p>	protected $str_version;</p>
<p>	/**<br />
	 * Constructor method<br />
	 * @param string str_dir The location of the Apache conf file to mod<br />
	 * @param string str_file The name of the Apache conf file to mod<br />
	 * @param string str_pre The needle to search for in the conf file<br />
	 */<br />
	function __construct($str_dir, $str_file, $str_pre) {</p>
<p>		$this-&gt;str_version = &#8216;ChangeLocalHost v0.1&#8242;;</p>
<p>		$this-&gt;arr_args = Array();<br />
		$this-&gt;bit_msgs = true;<br />
		$this-&gt;str_dir  = $str_dir;<br />
		$this-&gt;str_file = $str_file;<br />
		$this-&gt;str_pre  = $str_pre;</p>
<p>	}</p>
<p>	/**<br />
	 * Modify Apache&#8217;s DocumentRoot<br />
	 * @param string str_file The (conf) file to mod<br />
	 * @param string str_new_dir The new directory to set as DocumentRoot<br />
	 * @private<br />
	 */<br />
	private function alterLocalHost($str_file, $str_new_dir) {</p>
<p>		$str_contents = file_get_contents($str_file);</p>
<p>		if (!$str_contents) {<br />
			$this-&gt;showError(&#8217;Could not read &#8216; . $str_file);<br />
		}</p>
<p>		$int_begin    = strpos($str_contents, $this-&gt;str_pre);<br />
		$int_end      = strpos(substr($str_contents, $int_begin), &#8220;\n&#8221;);<br />
		$str_search   = substr($str_contents, $int_begin, $int_end);<br />
		$str_contents = str_replace($str_search, $str_new_dir, $str_contents);<br />
		$bit_written  = file_put_contents($str_file, $str_contents);</p>
<p>		if ($bit_written) {<br />
			$this-&gt;showMessage(&#8217;Successfully set DocumentRoot to &#8216; . $str_new_dir);<br />
		} else {<br />
			$this-&gt;showError(&#8217;Could not write &#8216; . $str_file);<br />
		}</p>
<p>	}</p>
<p>	/**<br />
	 * Validates the new directory to set<br />
	 * @param string str_new_dir The potential new directory<br />
	 * @private<br />
	 */<br />
	private function checkLocalHost($str_new_dir) {</p>
<p>		$str_set_to = $this-&gt;str_pre . $str_new_dir;</p>
<p>		if (is_dir($str_set_to)) {</p>
<p>			$this-&gt;setLocalHost($str_set_to);<br />
			$this-&gt;restartApache2();</p>
<p>		} else {<br />
			$this-&gt;showError($str_set_to . &#8216; is not a valid directory.&#8217;);<br />
		}</p>
<p>	}</p>
<p>	/**<br />
	 * Ensures this app is being executed as root<br />
	 * @private<br />
	 */<br />
	private function checkRoot() {</p>
<p>		// Make sure user is root<br />
		$str_command = &#8216;whoami&#8217;;</p>
<p>		exec($str_command, $arr_output, $int_return);</p>
<p>		if ($arr_output[0] != &#8216;root&#8217;) {<br />
			$this-&gt;showError(&#8217;You must be root to run this program.&#8217;);<br />
		}</p>
<p>	}</p>
<p>	/**<br />
	 * Makes a backup of the Apache conf file<br />
	 * @param string str_source The original to copy<br />
	 * @param string str_new The location of the backup<br />
	 * @return bool Whether the copy was successful or not<br />
	 * @private<br />
	 */<br />
	private function makeCopy($str_source, $str_new) {</p>
<p>		$bit_copy = copy($str_source, $str_new);</p>
<p>		if (!$bit_copy) {<br />
			$this-&gt;showError(&#8217;Could not make copy of &#8216; . $str_source);<br />
		}</p>
<p>		return true;</p>
<p>	}</p>
<p>	/**<br />
	 * Restarts Apache2<br />
	 * @private<br />
	 */<br />
	private function restartApache2() {</p>
<p>		$str_command = &#8216;apache2ctl restart&#8217;;</p>
<p>		exec($str_command, $arr_output, $int_return);</p>
<p>		if ($int_return &gt; 0) {<br />
			$this-&gt;showError(&#8217;Could not restart Apache2.&#8217; . $str_source);<br />
		}</p>
<p>		$this-&gt;showMessage(&#8217;Successfully restarted Apache2.&#8217;);</p>
<p>	}</p>
<p>	/**<br />
	 * Executes the script<br />
	 */<br />
	function run() {</p>
<p>		$this-&gt;checkRoot();</p>
<p>		$str_new_dir = $this-&gt;arr_args[1];</p>
<p>		switch ($this-&gt;arr_args[1]) {</p>
<p>			case &#8216;-c&#8217; :<br />
			case &#8216;&#8211;current&#8217; :<br />
				$this-&gt;showCurrent();<br />
				break;</p>
<p>			case &#8221; :<br />
			case &#8216;-h&#8217; :<br />
			case &#8216;&#8211;help&#8217; :<br />
				$this-&gt;showHelp();<br />
				break;</p>
<p>			case &#8216;-q&#8217; :<br />
			case &#8216;&#8211;quiet&#8217; :<br />
				$str_new_dir    = $this-&gt;arr_args[2];<br />
				$this-&gt;bit_msgs = false;<br />
				break;</p>
<p>			case &#8216;-v&#8217; :<br />
			case &#8216;&#8211;version&#8217; :<br />
				$this-&gt;showVersion();<br />
				break;</p>
<p>			default :<br />
				break;</p>
<p>		}</p>
<p>		$this-&gt;checkLocalHost($str_new_dir);<br />
		exit(0);</p>
<p>	}</p>
<p>	/**<br />
	 * Create a copy of the arguments global<br />
	 * @param array array_args The arguments to set<br />
	 */<br />
	function setArgs($arr_args) {<br />
		$this-&gt;arr_args = &amp;$arr_args;<br />
	}</p>
<p>	/**<br />
	 * Call the other methods to initiate the altering of the DocumentRoot<br />
	 * @param string str_new_dir The new value of DocumentRoot<br />
	 * @private<br />
	 */<br />
	private function setLocalHost($str_new_dir) {</p>
<p>		$str_ext    = &#8216;.bak&#8217;;<br />
		$str_file   = ($this-&gt;str_dir . $this-&gt;str_file);<br />
		$str_backup = $str_file . $str_ext;</p>
<p>		if (is_file($str_file)) {</p>
<p>			if ($this-&gt;makeCopy($str_file, $str_backup)) {<br />
				$this-&gt;showMessage(&#8217;Copied backup of &#8216; . $this-&gt;str_file . &#8216; to &#8216; . $this-&gt;str_file . $str_ext);<br />
			}</p>
<p>			$this-&gt;alterLocalHost($str_file, $str_new_dir);</p>
<p>		} else {<br />
			$this-&gt;showError($str_file . &#8216; cannot be found.&#8217;);<br />
		}</p>
<p>	}</p>
<p>	/**<br />
	 * Show what DocumentRoot is currently set to<br />
	 * @private<br />
	 */<br />
	private function showCurrent() {</p>
<p>		$str_file = ($this-&gt;str_dir . $this-&gt;str_file);</p>
<p>		if (is_file($str_file)) {</p>
<p>			$str_contents = file_get_contents($str_file);</p>
<p>			if (!$str_contents) {<br />
				$this-&gt;showError(&#8217;Could not read &#8216; . $str_file);<br />
			}</p>
<p>			$int_begin  = strpos($str_contents, $this-&gt;str_pre);<br />
			$int_end    = strpos(substr($str_contents, $int_begin), &#8220;\n&#8221;);<br />
			$str_search = substr($str_contents, $int_begin, $int_end);</p>
<p>			$this-&gt;showMessage(&#8217;The current DocumentRoot is: &#8216; . $str_search);<br />
			exit;</p>
<p>		} else {<br />
			$this-&gt;showError($str_file . &#8216; cannot be found.&#8217;);<br />
		}</p>
<p>	}</p>
<p>	/**<br />
	 * Display a message and exit<br />
	 * @param string str_error The message to display<br />
	 * @private<br />
	 */<br />
	private function showError($str_error) {</p>
<p>		echo &#8216;Error: &#8216; . $str_error . &#8220;\n&#8221;;</p>
<p>		exit(1);</p>
<p>	}</p>
<p>	/**<br />
	 * Show the help text and exit<br />
	 * @private<br />
	 */<br />
	private function showHelp() {</p>
<p>		$str_help .= &#8216;Usage: clh [DIRECTORY]&#8230; [OPTIONS]&#8216; . &#8220;\n&#8221;;<br />
		$str_help .= &#8216;Alter the DocumentRoot in Apache2.&#8217; . &#8220;\n&#8221;;<br />
		$str_help .= &#8220;\n&#8221;;<br />
		$str_help .= &#8216;  -c, &#8211;current  display current DocumentRoot and exit&#8217; . &#8220;\n&#8221;;<br />
		$str_help .= &#8216;  -h, &#8211;help     display this help and exit&#8217; . &#8220;\n&#8221;;<br />
		$str_help .= &#8216;  -q, &#8211;quiet    suppress most messages&#8217; . &#8220;\n&#8221;;<br />
		$str_help .= &#8216;  -v, &#8211;version  output version information and exit&#8217; . &#8220;\n&#8221;;<br />
		$str_help .= &#8220;\n&#8221;;<br />
		$str_help .= &#8216;Report bugs to &lt;scriptnode@gmail.com&gt;.&#8217; . &#8220;\n&#8221;; // Hahahaha</p>
<p>		echo $str_help;</p>
<p>		exit(0);</p>
<p>	}</p>
<p>	/**<br />
	 * Display a message to the user<br />
	 * @param string str_message The message to show<br />
	 * @private<br />
	 */<br />
	private function showMessage($str_message) {</p>
<p>		if ($this-&gt;bit_msgs) {<br />
			echo $str_message . &#8220;\n&#8221;;<br />
		}</p>
<p>	}</p>
<p>	/**<br />
	 * Attempt to be more like a real application by displaying the version<br />
	 * @private<br />
	 */<br />
	private function showVersion() {</p>
<p>		echo $this-&gt;str_version . &#8220;\n&#8221;;</p>
<p>		exit(0);</p>
<p>	}</p>
<p>}<br />
</textarea></p>
<p>
You&#8217;ll notice that the script is at least a year and a half old.<br />
Usually if code of mine is more than a year old, it&#8217;s completely unusuable because my <a href="/article/my-new-coding-habits/">habits change pretty often</a>.<br />
But I think I&#8217;ve finally gotten to that sweet spot where it&#8217;s not total garbage, it just needs tweaking.
</p>
<p>
I was surprised that the code isn&#8217;t too bad really. It&#8217;s easily readable and well organized. There are many things that I wouldn&#8217;t have done were I to write this again;<br />
for example, I stopped using type prefixes long ago (such as an array of users as <code>$arr_users</code>). I understand why I used to do this, but it&#8217;s not necessary<br />
and only clutters up the code.
</p>
<p>
Anyway, I find this script useful and I thought someone else might too. Enjoy!
</p>
<ul>
<li><a href="/assets/php/clh/clh.php.txt">[Download clh.php.txt]</a> (6,614 bytes)</li>
<li><a href="/assets/php/clh/clh.zip">[Download clh.zip]</a> (1,975 bytes)</li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://scriptnode.com/article/quickly-update-documentroot-in-apache2/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
