<?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; javascript</title>
	<atom:link href="http://scriptnode.com/tag/javascript/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>Simple Loading Bar</title>
		<link>http://scriptnode.com/article/simple-loading-bar/</link>
		<comments>http://scriptnode.com/article/simple-loading-bar/#comments</comments>
		<pubDate>Mon, 03 Aug 2009 06:56:36 +0000</pubDate>
		<dc:creator>Matt Hackett</dc:creator>
				<category><![CDATA[Novice]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[lab]]></category>
		<category><![CDATA[script-sunday]]></category>

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


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

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

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

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


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