<?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>nFriedly Web Dev Tech Blog &#187; javascript</title>
	<atom:link href="http://nfriedly.com/techblog/tag/javascript/feed/" rel="self" type="application/rss+xml" />
	<link>http://nfriedly.com/techblog</link>
	<description>Expert Advice on Website Development, Javascript, Ajax, and Security</description>
	<lastBuildDate>Tue, 20 Jul 2010 14:58:10 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0</generator>
		<item>
		<title>.swf for JavaScript cross-domain flash cookies</title>
		<link>http://nfriedly.com/techblog/2010/07/swf-for-javascript-cross-domain-flash-cookies/</link>
		<comments>http://nfriedly.com/techblog/2010/07/swf-for-javascript-cross-domain-flash-cookies/#comments</comments>
		<pubDate>Tue, 13 Jul 2010 18:25:11 +0000</pubDate>
		<dc:creator>nFriedly</dc:creator>
				<category><![CDATA[Web Development]]></category>
		<category><![CDATA[actionscript 3.0]]></category>
		<category><![CDATA[cookie]]></category>
		<category><![CDATA[cross-domain]]></category>
		<category><![CDATA[externalinterface]]></category>
		<category><![CDATA[flash]]></category>
		<category><![CDATA[flashcookie]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[sharedobject]]></category>
		<category><![CDATA[swf]]></category>

		<guid isPermaLink="false">http://nfriedly.com/techblog/?p=272</guid>
		<description><![CDATA[I&#8217;m working on a project that has a legitimate (non-spammy) reason to need cross-domain cookies, and we settled on flash as a good way to accomplish this. However, I was surprisingly unable to find any complete library or how-to guide for connecting flash cookies to javascript. So I dusted off my flash skills and built [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://nfriedly.com/techblog/2010/07/swf-for-javascript-cross-domain-flash-cookies/"><img class="alignright size-full wp-image-295" title="325990_chocolate_chip_cookies_2" src="http://nfriedly.com/techblog/wp-content/uploads/2010/07/325990_chocolate_chip_cookies_2.jpg" alt="" width="300" height="224" /></a>I&#8217;m working on a project that has a legitimate (non-spammy) reason to need cross-domain cookies, and we settled on flash as a good way to accomplish this.</p>
<p>However, I was surprisingly unable to find any complete library or how-to guide for connecting flash cookies to javascript. So I dusted off my flash skills and built one, and decided to share with you the fruits of my labors:</p>
<p><span id="more-272"></span></p>
<p><a href="http://github.com/nfriedly/Javascript-Flash-Cookies/zipball/master"><img class="alignleft" src="/img/application_put.png" alt="" /> Download the .swf, .js, and source code from github</a></p>
<p>This is an .swf file  that communicates with JavaScript via flash&#8217;s <a href="http://www.adobe.com/livedocs/flash/9.0/ActionScriptLangRefV3/flash/external/ExternalInterface.html">ExternalInerface</a> to read and write to a Local <a href="http://www.adobe.com/livedocs/flash/9.0/ActionScriptLangRefV3/flash/net/SharedObject.html">SharedObject</a> (LSO). Essentially, it&#8217;s cross-domain cookies for javascript.</p>
<p>It also includes a javascript library that handles embedding, error checking, and logging.</p>
<p>The project is hosted at github: <a href="http://github.com/nfriedly/Javascript-Flash-Cookies">http://github.com/nfriedly/Javascript-Flash-Cookies</a></p>
<h3>Quick start guide</h3>
<p>NOTE: A javascript library and an example have been added to the source code. That supersedes these instructions. Updated instructions and online examples coming soon. </p>
<p>To use the library, upload the storage.swf file to your web server and put this HTML and JavaScript into your web page(s):</p>
<h4>The JavaScript</h4>
<pre class="brush: jscript;">
	function getSwfStore(){
		return document.local_storage_swf || window.local_storage_swf;
	}

	function swfLogFn(msg){
		if(typeof console != &quot;undefined&quot; &amp;&amp; typeof console.log != &quot;undefined&quot;){
			console.log(&quot;.swf Storage: &quot; + msg);
		}
		else {
			alert(&quot;.swf Storage: &quot; + msg);
		}
	}

	function swfOnLoad(){
		var swfStore = getSwfStore();
		// read a cookie via swfStore.get('cookie_name');
		// set a cookie via swfStore.set('cookie_name', 'cookie_value');
	}

	function swfOnError(){
		alert('ut-oh, something went wrong (probably the user disabled flash cookies for privacy reasons)');
	}
</pre>
<h4>And the HTML</h4>
<pre class="brush: xml;">
&lt;span style=&quot;position: absolute; left: -1000px; top: -1000px;&quot;&gt;
	&lt;object height=&quot;100&quot; width=&quot;500&quot; codebase=&quot;http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab&quot; id=&quot;local_storage_swf&quot; classid=&quot;clsid:D27CDB6E-AE6D-11cf-96B8-444553540000&quot;&gt;
		&lt;param value=&quot; -- URL TO storage.swf -- &quot; name=&quot;movie&quot;&gt;
		&lt;param value=&quot;swfLogFn&quot; name=&quot;logfn&quot;&gt;
		&lt;param value=&quot;swfOnLoad&quot; name=&quot;onload&quot;&gt;
		&lt;param value=&quot;swfOnError&quot; name=&quot;onerror&quot;&gt;
		&lt;param value=&quot;logfn=swfLogFn&amp;amp;onload=swfOnLoad&amp;amp;onerror=swfOnError&quot; name=&quot;FlashVars&quot;&gt;
		&lt;param value=&quot;always&quot; name=&quot;allowScriptAccess&quot;&gt;
		&lt;embed height=&quot;375&quot; align=&quot;middle&quot; width=&quot;500&quot; pluginspage=&quot;http://www.macromedia.com/go/getflashplayer&quot; flashvars=&quot;logfn=swfLogFn&amp;amp;onload=swfOnLoad&amp;amp;onerror=swfOnError&quot; type=&quot;application/x-shockwave-flash&quot; allowscriptaccess=&quot;always&quot; quality=&quot;high&quot; loop=&quot;false&quot; play=&quot;true&quot; name=&quot;local_storage_swf&quot; bgcolor=&quot;#869ca7&quot; src=&quot; -- URL TO storage.swf -- &quot;&gt;
	&lt;/object&gt;
&lt;/span&gt;
</pre>
<h3>Cross-domain usage</h3>
<p>A copy of storage.swf located on one domain may be embedded on pages from one or more other domains, allowing cross-domain cookie access.</p>
<h3>Troubleshooting</h3>
<ul>
<li>Be sure to fill in the url to the .swf file in both the &lt;object&gt;  and the &lt;embed&gt; tags.</li>
<li>If you change the name of any of the  javascript functions, you must update the name in three places &lt;param&gt; and  &lt;embed&gt; tags.</li>
<li>If the .swf file is unable to communicate, it will display log messages on the flash object. You can remove the &lt;span&gt; tag that surrounds it and read those messages. (If the font is too small, try copy-pasting it.)</li>
<li>If the user does not have flash installed, neither the onload nor the onerror functions will be called. You may want to use a library such as <a href="http://www.featureblend.com/javascript-flash-detection-library.html">Flash Detect</a> to check for this.</li>
<li>If you pass a function as the key or value, things may break. Your best bet is to use strings and/or use<a href="json.org">JSON</a> to encode objects as strings</li>
</ul>
<h3>Patches</h3>
<p>My flash / actionscript skills leave something to be desired, and patches are more than welcome at  <a href="http://github.com/nfriedly/Javascript-Flash-Cookies">github</a> (prefered), or just leave a comment here if you&#8217;re not sure how to use github.</p>
]]></content:encoded>
			<wfw:commentRss>http://nfriedly.com/techblog/2010/07/swf-for-javascript-cross-domain-flash-cookies/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>How to use XSLT to style an RSS feed</title>
		<link>http://nfriedly.com/techblog/2009/06/how-to-use-xslt-to-style-an-rss-feed/</link>
		<comments>http://nfriedly.com/techblog/2009/06/how-to-use-xslt-to-style-an-rss-feed/#comments</comments>
		<pubDate>Wed, 17 Jun 2009 19:18:39 +0000</pubDate>
		<dc:creator>nFriedly</dc:creator>
				<category><![CDATA[Web Development]]></category>
		<category><![CDATA[css]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[php]]></category>
		<category><![CDATA[rss]]></category>
		<category><![CDATA[xml]]></category>
		<category><![CDATA[xslt]]></category>

		<guid isPermaLink="false">http://nfriedly.com/techblog/?p=191</guid>
		<description><![CDATA[XSLT is a fairly well-supported technology. It allows you to take any XML file &#8211; including RSS &#8211; and transform it into a styled HTML document. It&#8217;s kind of like CSS on steroids. Unfortunately, most browsers think they know better and go off and do their own thing on RSS feeds. We&#8217;re going to look [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://www.flickr.com/photos/gogdog/2240855570/"><img src="http://farm3.static.flickr.com/2097/2240855570_4529cf9f6d_m.jpg" alt="Take this!" class="alignright"  /></a><abbr title="Extensible Stylesheet Language Transformations">XSLT</abbr> is a fairly well-supported technology. It allows you to take any XML file &#8211; including RSS &#8211; and <i>transform</i> it into a styled HTML document. It&#8217;s kind of like CSS on steroids.</p>
<p>Unfortunately, most browsers think they know better and go off and do their own thing on RSS feeds.</p>
<p>We&#8217;re going to look at how and which browsers can be brought into line, and how to use XSLT to improve the look of your RSS feed in those browsers.</p>
<p><span id="more-191"></span></p>
<h2>The RSS problem</h2>
<p>In most browsers, XML and XSLT are supported in every single case *except* RSS. By default, Internet Explorer, Firefox, Safari, and Opera all ignore XSLT files and do their own thing with RSS. In fact, Google Chrome is the *only* browser I tested that got it right without tinkering.</p>
<p>To their credit, Microsoft at least gave their users the option to turn off the &#8220;feature&#8221;. No other browser even gives this option.</p>
<p>During my tests, I have found a way to &#8220;trick&#8221; Firefox into rendering RSS with XSLT correctly. Currently there seems to be no solution for other browsers except to try and detect them on the server and send the user an HTML file if they&#8217;re in a browser that doesn&#8217;t work properly.</p>
<h3>Internet Explorer</h3>
<p>IE requires that the user specifically choose to disable their take-liberties-with-rss &#8220;feature&#8221;. I would point out that this really isn&#8217;t good enough because 99% of users will never get that far, but sadly, it&#8217;s the closest thing to getting it right out of any browser on the market!</p>
<p>Here&#8217;s how:</p>
<ol>
<li>Click on the <strong>Tools</strong> menu,</li>
<li>Click on the <strong>Internet Options</strong> sub-menu,</li>
<li>Click on the <strong>Content</strong> tab,</li>
<li>Click on the <strong>Settings</strong> button of the <strong>Feed</strong> section to bring up Feed Settings dialog box,</li>
<li>Un-check the <strong>Turn On Feed Reading View</strong> option.</li>
<li>Click OK all the way to close all opened dialog boxes.</li>
<li>Restart Internet Explorer</li>
</ol>
<h3><a href="http://www.flickr.com/photos/gogdog/2240065731/"><img src="http://farm3.static.flickr.com/2172/2240065731_86c22f48c1_m.jpg" alt="Transform!" class="alignright" /></a>Firefox</h3>
<p>Firefox can be tricked into working because it decides fairly early on in the rendering process whether to treat the page in a standard way or to fly off the handle with it. In fact, it makes this decision before even completely downloading the RSS file.</p>
<p>Because of the early decision process, we can insert 512 characters of white space in between the <code>&lt;?xml ?&gt;</code> declaration and the opening <code>&lt;rss&gt;</code> tag. Firefox is then &#8220;tricked&#8221; into doing the right thing and rendering the feed correctly.</p>
<h2>Working around it</h2>
<p>Although not practical in most cases currently, I&#8217;ve included an example of a script that will take any RSS feed and add a style sheet to it.  It includes the hack to work in firefox and instructions for enabling it in Internet Explorer.</p>
<p><a href="http://nfriedly.com/stuff/rss/?url=http://nfriedly.com/techblog/feed/">http://nfriedly.com/stuff/rss/?url=http://nfriedly.com/techblog/feed/</a></p>
<p>Code for index.php:</p>
<pre class="brush: php;">
&lt;?php

// grab the url
if(isset($_REQUEST['url'])) $url = $_REQUEST['url'];
else $url = false;

// make sure the url is good (no local files)
if($url &amp;&amp; substr($url,0,7) != &quot;http://&quot;) exit(&quot;Please start urls with 'http://'&quot;);

// make the stylesheet link
$xsl_file = 'xsl.php';
if($url) $xsl_file .= '?url='.urlencode($url);
define('XSL_LINK','&lt;?xml-stylesheet href=&quot;'.$xsl_file.'&quot; type=&quot;text/xsl&quot; ?&gt;');

// if we don't have a url, use the home page
if(!$url) $url = &quot;home.xml&quot;;

// download the rss feed
$rss = file_get_contents($url);

// xml header so firefox doesn't decide it's text
header('content-type: text/xml');

//echo out the header right away, if there is one
if(substr($rss,0,6) == '&lt;?xml '){
	$header_end = strpos($rss,'?&gt;') +2;
	echo substr($rss,0,$header_end);
	$rss = substr($rss,$header_end);
}
//otherwise echo a default header:
else echo '&lt;?xml version=&quot;1.0&quot; ?'.'&gt;';

// remove any existing stylesheet
$rss = preg_replace('/&lt;\?xml-stylesheet([^?]|\?(?!&gt;))*\?'.'&gt;/','',$rss);  // uses lookahead

// add in our stylesheet
echo &quot;\r\n&quot; . XSL_LINK . &quot;\r\n&quot;;

// toss in 512 bytes of nothing to throw off firefox
echo &quot;                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                 &quot;;

//finally, pass along the content
echo $rss;

?&gt;
</pre>
<p>The xsl.php file is only php to allow for setting the current url in the feed url input box. Ignoring that, you can view it&#8217;s source by looking at <a href="http://nfriedly.com/stuff/rss/xsl.php">http://nfriedly.com/stuff/rss/xsl.php</a>. You could simply save that as an .xml file and have a working copy.</p>
<p>You can also view the <a href="http://nfriedly.com/stuff/rss/theme/style.css">CSS</a> and <a href="http://nfriedly.com/stuff/rss/scripts.js">Javascript</a> used to make everything look nice. </p>
<h2>Hire me for web development</h2>
<p>Need an <a href="http://nfriedly.com/webdev">expert web programmer</a> to research and solve some off-the-wall problem like this? I&#8217;m available. I&#8217;m good solving run-of-the-mill problems too &#8211; <a href="http://nfriedly.com/webdev/javascript">Javascript and AJAX development</a> is my specialty.  <a href="http://nfriedly.com/contact">Get in touch with me</a> for more information and a free quote.</p>
]]></content:encoded>
			<wfw:commentRss>http://nfriedly.com/techblog/2009/06/how-to-use-xslt-to-style-an-rss-feed/feed/</wfw:commentRss>
		<slash:comments>16</slash:comments>
		</item>
		<item>
		<title>How AJAX Security and Twitter callbacks work</title>
		<link>http://nfriedly.com/techblog/2009/06/javascript-security-ajax-json-and-twitter-callbacks/</link>
		<comments>http://nfriedly.com/techblog/2009/06/javascript-security-ajax-json-and-twitter-callbacks/#comments</comments>
		<pubDate>Tue, 16 Jun 2009 14:40:33 +0000</pubDate>
		<dc:creator>nFriedly</dc:creator>
				<category><![CDATA[Web Development]]></category>
		<category><![CDATA[ajax]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[json]]></category>
		<category><![CDATA[security]]></category>
		<category><![CDATA[twitter]]></category>

		<guid isPermaLink="false">http://nfriedly.com/techblog/2009/06/javascript-security-ajax-json-and-twitter-callbacks/</guid>
		<description><![CDATA[The twitter callback feature is nice &#8211; it makes it extremely easy to to add a twitter feed to a page. But to get the most benefit out of it, you really need to understand what it&#8217;s doing. We&#8217;re going to look at how AJAX security works, specifically the Same Origin Policy, how Twitter gets [...]]]></description>
			<content:encoded><![CDATA[<p><img class="alignleft" title="Breaking javascript - the right way" src="http://www.sxc.hu/pic/m/s/si/simonok/323276_game_of_pool.jpg" alt="" width="141" height="188" />The twitter callback feature is nice &#8211; it makes it extremely easy to to add a twitter feed to a page. But to get the most benefit out of it, you really need to understand what it&#8217;s doing.</p>
<p>We&#8217;re going to look at how AJAX security works, specifically the Same Origin Policy, how Twitter gets around it, and the type of callback that twitter uses.</p>
<p>Note: the callback that twitter uses is entirely different from callback in the sense of passing a javascript function around as a variable. We&#8217;ll look at that in a future article.</p>
<p><span id="more-114"></span></p>
<h2>AJAX Security</h2>
<p>The XMLHTTPRequest Object, which is the javascript object used to make AJAX requests, has a &#8220;<a href="https://developer.mozilla.org/En/Same_origin_policy_for_JavaScript">Same Origin Policy</a>&#8221; which basically means that javascript on site1.com cannot use AJAX to directly load data from site2.com. This is a security feature, as it makes XSS (Cross-Site Scripting) attacks more difficult.</p>
<p>Worth noting, if the website is at site1.com, no scripts can communicate with any other site, even if the script was loaded from site2.com.</p>
<h2>Work Arounds</h2>
<p>There are a number of workarounds including iframes, java applets, and flash, but here&#8217;s a couple of the more common methods.</p>
<h3><img src="http://www.sxc.hu/pic/m/c/cw/cwmgary/486891_all_lined_up.jpg" alt="Line em up!" class="alignright" />Proxying Requests</h3>
<p>The way proxying works is to have a file on your server that grabs the data from a remote server and passes it along. Then for javascript, the data appears to be coming from your server, even though it actually originated at a remote server. This is what the Fancy part of my <a href="http://nfriedly.com/demos/twitter">twitter demo</a> does.</p>
<p>We&#8217;ll look at using a proxy to get remote data in a future article.</p>
<h3>Remotely hosted javascript files</h3>
<p>Scripts stored on other websites can be included on a page. As long as the script doesn&#8217;t need to call home after the initial load, everything works great. This is how a basic twitter function works: you load a script from twitter&#8217;s website and it communicates with your site via the callback feature. This is what the Simple part of my <a href="http://nfriedly.com/demos/twitter">twitter demo</a> does.</p>
<p>Here is a very basic page that uses Twitter&#8217;s callback feature and a remotely loaded javascript file to show my twitter status &#8211; remote data &#8211; on my website, by interacting with local javascript.</p>
<pre class="brush: xml;">
&lt;!DOCTYPE html PUBLIC &quot;-//W3C//DTD XHTML 1.0 Transitional//EN&quot; &quot;http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd&quot;&gt;
&lt;html xmlns=&quot;http://www.w3.org/1999/xhtml&quot;  dir=&quot;ltr&quot; lang=&quot;en-US&quot;&gt;

&lt;head&gt;
&lt;title&gt;Simple Twitter Status&lt;/title&gt;

&lt;/head&gt;
&lt;body&gt;

&lt;h1&gt;My Twitter Status:&lt;/h1&gt;

&lt;div id=&quot;twitter_status&quot;&gt;Loading...&lt;/div&gt;

&lt;!-- Put scripts down here for speed --&gt;

&lt;!-- this must come before we load the twitter script --&gt;
&lt;script type=&quot;text/javascript&quot;&gt;

function showStatus(json){

	json = json[0]; // we only care about the most recent status;

	var myDiv = document.getElementById('twitter_status');

	myDiv.innerHTML = '&lt;img src=&quot;'
		+ json.user.profile_image_url
		+ '&quot; style=&quot;float:left; margin:5px 10px 10px 0&quot;&gt;'
		+ json.text;
}
&lt;/script&gt;

&lt;!-- now load the twitter file --&gt;
&lt;script type=&quot;text/javascript&quot;
src=&quot;http://twitter.com/statuses/user_timeline/nfriedly.json?count=1&amp;amp;callback=showStatus&amp;amp;random=&lt;?php echo time(); ?&gt;&quot; /&gt;
&lt;/script&gt;

&lt;/body&gt;
&lt;/html&gt;
</pre>
<p>You can see a live copy of this code at <a href="http://nfriedly.com/demos/twitter-extra-simple">http://nfriedly.com/demos/twitter-extra-simple</a>.</p>
<h2>Digging into Twitter&#8217;s callback method</h2>
<p>Below is a trimmed down example of what Twitter&#8217;s API sends back when we make the request in the example above.</p>
<pre class="brush: jscript;">
showStatus([{&quot;in_reply_to_screen_name&quot;:null,&quot;text&quot;:&quot; [ Lots of information that I'm omitting because it's not the point. ] &quot;]);
</pre>
<p>Now, don&#8217;t worry about the jazz in the middle, just look at that showStatus(); that&#8217;s wrapped around it. First of all, how does Twitter even know that we have a function named show status? Because we said so in the url to the file -see how we added <code>&amp;callback=showStatus</code>? That&#8217;s where the magic is.  (Ok, technically we said <code>&amp;amp;</code> not just <code>&amp;</code>, but that was just to pass XHTML validation. )</p>
<p><img class="alignright" title="The break!" src="http://www.sxc.hu/pic/m/l/lj/ljweb/490307_pool_break.jpg" alt="" width="300" height="168" /></p>
<h3>Cross-domain!</h3>
<p>There&#8217;s a second important thing going on here &#8211; javascript from two different domains are interacting with each other. This is allowed because of how the Same Origin Policy works &#8211; everything is restricted to the local domain, but that means that everything can work together on the same plane.</p>
<h3>It&#8217;s a beautiful thing</h3>
<p>I hope this gave you a little bit better understanding of how AJAX security works and how Twitter gets around it and is still able to interact with your site. In the future, I&#8217;ll have an article on how &#8220;traditional&#8221; callbacks work that will use jQuery and more AJAX to dive a bit deeper into the topic.</p>
<h2>Javascript Ninja for Hire</h2>
<p>I have <a href="http://nfriedly.com/portfolio">extensive experience</a> working with AJAX, Twitter, and related technologies. I&#8217;m just the man you need to make your next <a href="http://nfriedly.com/webdev">javascript development</a> project shine!</p>
]]></content:encoded>
			<wfw:commentRss>http://nfriedly.com/techblog/2009/06/javascript-security-ajax-json-and-twitter-callbacks/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Advanced Javascript: Objects, Arrays, and Array-Like objects</title>
		<link>http://nfriedly.com/techblog/2009/06/advanced-javascript-objects-arrays-and-array-like-objects/</link>
		<comments>http://nfriedly.com/techblog/2009/06/advanced-javascript-objects-arrays-and-array-like-objects/#comments</comments>
		<pubDate>Wed, 10 Jun 2009 19:45:48 +0000</pubDate>
		<dc:creator>nFriedly</dc:creator>
				<category><![CDATA[Web Development]]></category>
		<category><![CDATA[javascript]]></category>

		<guid isPermaLink="false">http://nfriedly.com/techblog/?p=106</guid>
		<description><![CDATA[Javascript objects and arrays are both incredibly useful. They&#8217;re also incredibly easy to confuse with each other. Mix in a few objects that look like arrays and you&#8217;ve got a recipe for confusion! We&#8217;re going to see what the differences between objects and arrays are, how to work with some of the common array-like objects, [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://www.flickr.com/photos/stawarz/2492636763/"><img class="alignleft" title="The other kind of array" src="http://farm4.static.flickr.com/3146/2492636763_788774987e_m.jpg" alt="" width="240" height="160" /></a>Javascript <code>objects</code> and <code>arrays</code> are both incredibly useful. They&#8217;re also incredibly easy to confuse with each other. Mix in a few objects that look like arrays and you&#8217;ve got a recipe for confusion!</p>
<p>We&#8217;re going to see what the differences between objects and arrays are, how to work with some of the common array-like objects, and how to get the most performance out of each.</p>
<p><span id="more-106"></span></p>
<h2>What Objects Are</h2>
<p>A javascript object is a basic data structure:</p>
<pre class="brush: jscript;">

var basicObj = {}; // an empty object
// {} is a shortcut for &quot;new Object()&quot;

basicObj.suprise= &quot;cake!&quot;;

basicObj['suprise']; // returns &quot;cake!&quot;
</pre>
<p>Using <code>{}</code> instead of <code>new Object();</code> is know as &#8220;Object Literal&#8221; syntax.</p>
<pre class="brush: jscript;">
var fancyObj = {

	favoriteFood: &quot;pizza&quot;,

	add: function(a, b){

		return a + b;
	}
};

fancyObj.add(2,3); // returns 5

fancyObj['add'](2,3); // ditto.
</pre>
<p>As you can see, and probably already knew, properties can be accessed a couple of different ways.  However, it&#8217;s an important point that we&#8217;ll come back to in a minute.</p>
<p>Everything in javascript is an <code>object</code>. Everything. <code>Arrays</code>, <code>functions</code>, even <code>numbers</code>! Because of this, you can do some really interesting things, such as modifying the <code>prototypes</code> of Objects, Arrays, etc.</p>
<pre class="brush: jscript;">

// an example of something you probably shouldn't do. Ever. Seriously.

Number.prototype.addto = function(x){

	return this + x;

}

(8).addto(9); // returns 17

// other variations:

8.addto(9); 
// gives a syntax error, because the dot is assumed to be a decimal point

8['addto'](9); 
// works but is kind of ugly compared to the first method

var eight = 8;
eight.addto(9);  // works
</pre>
<h2>What Arrays Are</h2>
<p>Javascript arrays are a type of <code>object</code> used for storing multiple values in a single variable. Each value gets  numeric index and may be any data type.</p>
<pre class="brush: jscript;">
var arr = [];  // this is a shortcut for new Array();

arr[0] = &quot;cat&quot;;
arr[1] = &quot;mouse&quot;;
</pre>
<p>See how that syntax is so similar to the syntax used for setting object properties? In fact, the only difference is that objects use a string while arrays use a number. This is why arrays get confused with objects so often.</p>
<h3>Length</h3>
<p>Arrays have a <code>length</code> property that tells how many items are in the array and is automatically updated when you add or remove items to the array. </p>
<pre class="brush: jscript;">
var arr = [];

arr[0] = &quot;cat&quot;; // this adds to the array
arr[1] = &quot;mouse&quot;; // this adds to the array
arr[&quot;favoriteFood&quot;] = &quot;pizza&quot;; // this DOES NOT add to the array
// setting a string parameter adds to the underlying object

arr.length; // returns 2, not 3
</pre>
<p>The length property is only modified when you add an item to the array, not the underlying object.</p>
<p><strong>The <code>length</code> is always 1 higher than the highest index, even if there are actually fewer items in the array.</strong></p>
<pre class="brush: jscript;">

var arr = [];

arr.length; // returns 0;

arr[100] = &quot;this is the only item in the array&quot;;

arr.length;
// returns 101, even though there is only 1 object in the array
</pre>
<p>This is somewhat counter-intuitive. PHP does more what you would expect:</p>
<pre class="brush: php;">
&lt;?php

arr = array();

arr[100] = &quot;php behaves differently&quot;;

sizeof(arr); // returns 1 in PHP

?&gt;
</pre>
<p>You can manually set the <code>length</code> also. Setting it to 0 is a simple way to empty an array.</p>
<p>In addition to this length property, arrays have lots of nifty built in functions such as <code>push()</code>, <code>pop()</code>, <code>sort()</code>, <code>slice()</code>, <code>splice()</code>, and more. This is what sets them apart from Array-Like Objects.</p>
<h2><a href="http://www.flickr.com/photos/repoort/2645497916/"><img class="alignright" title="It's like an array, but made out of Lego!" src="http://farm4.static.flickr.com/3175/2645497916_386b9b75b8_m.jpg" alt="" width="240" height="180" /></a></h2>
<h2>Array-like Objects</h2>
<p>Array-like objects look like arrays. They have various numbered elements and a length property. But that&#8217;s where the similarity stops. Array-like objects do not have any of Array&#8217;s functions, and for-in loops don&#8217;t even work!</p>
<p>You&#8217;ll come across these more often than you might expect. A common one is the <code>arguments</code> variable that is present inside of every js function. </p>
<p>Also included in the category are the HTML node sets returned by <code>document.getElementsByTagName()</code>, <code>document.forms</code>, and basically every other DOM method and property that gives a list of items.</p>
<pre class="brush: jscript;">

document.forms.length; // returns 1;

document.forms[0]; // returns a form element.

document.forms.join(&quot;, &quot;); // throws a type error. this is not an array.

typeof document.forms; // returns &quot;object&quot;
</pre>
<p>Did you know you can send any number of parameters you want to a javascript function? They&#8217;re all stored in an array-like object named <code>arguments</code>.</p>
<pre class="brush: jscript;">

function takesTwoParams(a, b){

	// arguments is an  array-like variable inside of all functions
	// arguments.length works great

	alert (&quot;you gave me &quot;+arguments.length+&quot; parameters&quot;);  

	for(i=0; i&lt; arguments.length; i++){

		alert(&quot;parameter &quot; + i + &quot; = &quot; + arguments[i]); 

	}
}

takesTwoParams(&quot;one&quot;,&quot;two&quot;,&quot;three&quot;);
// alerts &quot;you gave me 3 parameter&quot;,
// then &quot;parameter 0 = one&quot;
// etc. 
</pre>
<p>This works great. But that&#8217;s about as far as you can go with array-like objects. The flowing example does not work:</p>
<pre class="brush: jscript;">

function takesTwoParams(a, b){

	alert(&quot; your parameters were &quot; + arguments.join(&quot;, &quot;));
	// throws a type error because arguments.join doesn't exist
}
</pre>
<h3>So what can you do? </h3>
<p>Well you could make your own <code>join()</code> function, but that adds a lot of unnecessary overhead to your code because it has to loop over everything. If only there were a quick way to get an array out of an array like object&#8230;</p>
<p>It turns out there is.</p>
<p>The array functions can be called on non-array objects as long as you know where to find the function (usually they&#8217;re attached to the array, but this isn&#8217;t an array remember <img src='http://nfriedly.com/techblog/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /> </p>
<p><code>Prototype</code> to the win:</p>
<pre class="brush: jscript;">
function takesTwoParams(a, b){

	var args = Array.prototype.slice.call(arguments);

	alert(&quot; your parameters were &quot; + args.join(&quot;, &quot;));
	// yay, this works!

}
</pre>
<p>Let&#8217;s take a look at that a bit more in-depth:</p>
<p><code>Array</code>: This object is the original array that all other arrays inherit their properties from.</p>
<p><code>Array.prototype</code>:This gives us access to all the methods properties that each array inherits</p>
<p><code>Array.prototype.slice</code>: The original slice method that is given to all arrays via the prototype chain. We can&#8217;t call it directly though, because when it runs internally, it looks at the <code>this</code> keyword, and calling it here would make <code>this</code> point to <code>Array</code>, not our <code>arguments</code> variable.</p>
<p><code>Array.prototype.slice.call()</code>: <code>call()</code> and <code>apply()</code> are prototype methods of the <code>Function</code> object, meaning that they can be called on every function in javascript. These allow you to change what the <code>this</code> variable points to inside a given function.</p>
<p>And finally, you get a regular <code>array</code> back! This works because javascript returns a new object of type Array rather than whatever you gave it. This causes a lot of headaches for a <a href="http://dean.edwards.name/weblog/2006/11/hooray/">few</a> <a href="http://webreflection.blogspot.com/2008/03/sorry-dean-but-i-subclassed-array-again.html">people</a> who are trying to make subclasses of Array, but it&#8217;s very handy in our case!</p>
<h2><a name="gotchas"></a>Gotchas</h2>
<p>First, in Internet Explorer, DOM <code>NodeLists</code> are not considered to be javascript objects, so you cannot call <code>Array.prototype.slice</code> on them. If you want an array, you&#8217;ll have to loop through it the old fashioned way. Or use a hybrid function that tries it the fast way first, then the slow way if that doesn&#8217;t work. </p>
<pre class="brush: jscript;">
function hybridToArray(nodes){
	try{
		// works in every browser except IE
		var arr = Array.prototype.slice.call(nodes);
		return arr;
	} catch(err){
		// slower, but works in IE
		var arr = [],
		    length = nodes.length;
		for(var i=0; i &lt; length; i++){
			arr.push(nodes[i]);
		}
		return arr;
	}
}
</pre>
<p>See an example here: <a href="http://nfriedly.com/demos/ie-nodelist-to-array">http://nfriedly.com/demos/ie-nodelist-to-array</a>.</p>
<p>Second, arrays are objects, so you can do this, but it can get you some serious inconsistencies:</p>
<pre class="brush: jscript;">

arr = [];

arr[0] = &quot;first element&quot;; // adds item to the array

arr.length; // returns 1

arr.two = &quot;second element&quot;; // adds an item to the underlying object that array is built on top of.

arr.length; // still returns 1 !

// BUT...
for(i in arr){

	// this will hit both 0 and &quot;two&quot;

}
</pre>
<h3>A better solution: wrap arrays in an object if you need both worlds</h3>
<p>This is basically a less efficient method of the array subclassing links I mentioned above. While less efficient, it has the advantage of being simple and reliable.</p>
<p>That said, I wouldn&#8217;t recommend that you use this in most cases due to issues with speed and extra code requirements. It&#8217;s provided here as an example.</p>
<pre class="brush: jscript;">
// an example of a wrapper for an array.
// not recommended for most situations.

var ArrayContainer = function(arr){

	this.arr = arr || [];

	this.length = this.arr.length;

};

ArrayContainer.prototype.add=  function(item){

	index = this.arr.length;

	this.arr[index] = item;

	this.length = this.arr.length;

	return index;

};

ArrayContainer.prototype.get=  function(index){

	return this.arr[index];

};

ArrayContainer.prototype.forEach=  function(fn){

	if(this.arr.forEach) this.arr.forEach(fn);// use native code if it's there

	else {

		for(i in this.arr){

			fn( i, this.arr[i], this.arr );

		}
	}
};

var mySuperDooperArray = new ArrayContainer();
</pre>
<p>Now that your array is (somewhat) protected on the inside, you can loop through it&#8217;s items with <code>forEach()</code> and know that they will match it&#8217;s length. You can also add arbitrary properties to <code>ArrayContainer</code> or <code>mySuperDooperArray</code> and they <strong>won&#8217;t</strong> get pulled into your <code>forEach()</code> loop.</p>
<p>This example could be extended to completely protect the array if the need arose. </p>
<h2>An Even Better Solution: <a href="http://nfriedly.com/webdev">Hire a javascript expert</a>.</h2>
<p>nFriedly Web Development is a top ranked <a href="http://nfriedly.com/webdev/javascript">Javascript and AJAX ninja</a> with an extensive portfolio of proven results. I can bring your project to life and make it run faster than you ever imagined.  <a href="http://nfriedly.com/contact">Get in touch</a> with me or get a free <a href="http://nfriedly.com/estimate">instant estimate</a> for new projects.</p>
]]></content:encoded>
			<wfw:commentRss>http://nfriedly.com/techblog/2009/06/advanced-javascript-objects-arrays-and-array-like-objects/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>Advanced Javascript: Logical Operators and truthy / falsy</title>
		<link>http://nfriedly.com/techblog/2009/06/advanced-javascript-operators-and-truthy-falsy/</link>
		<comments>http://nfriedly.com/techblog/2009/06/advanced-javascript-operators-and-truthy-falsy/#comments</comments>
		<pubDate>Sun, 07 Jun 2009 19:54:49 +0000</pubDate>
		<dc:creator>nFriedly</dc:creator>
				<category><![CDATA[Web Development]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[optimization]]></category>

		<guid isPermaLink="false">http://nfriedly.com/techblog/?p=46</guid>
		<description><![CDATA[Nearly every website on the internet uses javascript in some form or fashion. Yet very few people, even those who write it and teach it, have a clear understanding of how javascript works! Logical Operators are a core part of the language. We&#8217;re going to look at what logical operators are, what &#8220;truthy&#8221; and &#8220;falsy&#8221; [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://www.flickr.com/photos/fleur-design/308974073/"><img class="alignleft" title="speed machine" src="http://farm1.static.flickr.com/104/308974073_9057064747_m.jpg" alt="" width="240" height="160" /></a> Nearly every website on the internet uses javascript in some form or fashion. Yet very few people, even those who write it and teach it, have a clear understanding of how javascript works!</p>
<p>Logical Operators are a core part of the language. We&#8217;re going to look at what logical operators are, what &#8220;truthy&#8221; and &#8220;falsy&#8221; mean, and <strong>how to use this to write cleaner, faster and more optimized javascript</strong>.</p>
<p><span id="more-46"></span></p>
<h2>Javascript Logical Operators</h2>
<p>In traditional programming, operators such as <code>&amp;&amp;</code> and <code>|| </code> returned a boolean value (<code>true</code> or <code>false</code>). This is not the case in javascript. Here it returns the actual <code>object</code>, not a <code>true</code> / <code>false</code>.  To really explain this, I first have to explain what is truthy and what is falsy.</p>
<h3>Truthy or Falsy</h3>
<p>When javascript is expecting a <code>boolean</code> and it&#8217;s given something else, it decides whether the something else is &#8220;truthy&#8221; or &#8220;falsy&#8221;.</p>
<p>An empty string (<code>''</code>), the number <code>0</code>, <code>null</code>, <code>NaN</code>, a boolean <code>FALSE</code>, and <code>undefined</code> variables  are all &#8220;falsy&#8221;. Everything else is &#8220;truthy&#8221;.</p>
<pre class="brush: jscript;">
var emptyString = &quot;&quot;; // falsy

var nonEmptyString = &quot;this is text&quot;; // truthy

var numberZero = 0; // falsy

var numberOne = 1; // truthy

var emptyArray = []; // truthy, BUT []==false is true. More below.

var emptyObject = {}; // truthy

var notANumber = 5 / &quot;tree&quot;; // falsy
// NaN is a special javascript object for &quot;Not a Number&quot;.

function exampleFunction(){
alert(&quot;Test&quot;);
}
// examleFunction is truthy
// BUT exampleFunction() is falsy because it has no return (undefined)
</pre>
<p>Gotchas to watch out for: the strings &#8220;0&#8243; and &#8220;false&#8221; are both considered truthy.  You can convert a string to a number by multiplying it by 1.</p>
<pre class="brush: jscript;">
var test = &quot;0&quot;; // this is a string, not a number

(test == false); // returns false, meaning that test is truthy

(test * 1 == false); // returns true, meaning that test is now falsy
</pre>
<p>As one commenter <a href="#comment-2100">mentioned</a>, arrays are particularly weird. If you just test it for truthyness, an empty array is truthy. HOWEVER, if you compare an empty array to a boolean, it becomes falsy:</p>
<pre class="brush: jscript;">
  if([] == false){
    // this code runs
  }

  if( [] ) {
    // this code also runs
  }

  if([] == true){
    // this code doesn't run
  }

  if( ![] ) {
    // this code also doesn't run
  }
</pre>
<p>Another commenter <a href="http://www.nicollet.net/2009/06/the-truth-of-javascript/">pointed out</a> an additional gotcha to watch out for: while javascript evaluates empty arrays as true, PHP evaluates them as false.</p>
<p>PHP also evaluates &#8220;0&#8243; as falsy. (However &#8220;false&#8221; is evaluated as truthy by both PHP and javascript.)</p>
<pre class="brush: php;">
&lt;?php

$emptyArray = array(); // falsy in PHP

$stringZero = &quot;0&quot;; // falsy in PHP

?&gt;
</pre>
<h3>How Logical Operators Work</h3>
<h4>Logical OR, <code>||</code></h4>
<p>The logical OR operator, <code>||</code>,  is very simple after you understand what it is doing. If the first object is truthy, that gets returned. Otherwise, the second object gets returned.</p>
<pre class="brush: jscript;">
(&quot;test one&quot; || &quot;test two&quot;); // returns &quot;test one&quot;

(&quot;test one&quot; || &quot;&quot;); // returns &quot;test one&quot;

(0 || &quot;test two&quot;); // returns &quot;Test two&quot;

(0 || false); // returns false
</pre>
<p>Where would you ever use this? The OR operator allows you to easily specify default variables in a function.</p>
<pre class="brush: jscript;">
function sayHi(name){

var name = name || &quot;Dave&quot;;

alert(&quot;Hi &quot; + name);

}

sayHi(&quot;Nathan&quot;); // alerts &quot;Hi Nathan&quot;;

sayHi(); // alerts &quot;Hi Dave&quot;,
// name is set to null when the function is started
</pre>
<h4>Logical AND, <code>&amp;&amp;</code></h4>
<p>The logical AND operator, <code>&amp;&amp;</code>,  works similarly.  If the first object is falsy, it returns that object. If it is truthy, it returns the second object.</p>
<pre class="brush: jscript;">
(&quot;test one&quot; &amp;&amp; &quot;test two&quot;); // returns &quot;test two&quot;

(&quot;test one&quot; &amp;&amp; &quot;&quot;); // returns &quot;&quot;

(0 &amp;&amp; &quot;test two&quot;) // returns 0
</pre>
<p>The logical AND allows you to make one variable dependent on another.</p>
<pre class="brush: jscript;">
var checkbox = document.getElementById(&quot;agreeToTerms&quot;);

var name = checkbox.checked &amp;amp;&amp;amp; prompt(&quot;What is your name&quot;);

// name is either their name, or false if they haven't checked the AgreeToTerms checkbox

// IMPORTANT NOTE: Internet Explorer 8 breaks the prompt function.
</pre>
<h4>Logical NOT, <code>!</code></h4>
<p>Unlike <code>&amp;&amp;</code> and <code>||</code>, the <code>!</code> operator DOES turn the value it receives into a boolean. If it receives a truthy value, it returns <code>false</code>, and if it receives a falsy value, it returns <code>true</code>.</p>
<pre class="brush: jscript;">
(!&quot;test one&quot; || &quot;test two&quot;); // returns &quot;test two&quot;
// (&quot;test one&quot; gets converted to false and skipped)

(!&quot;test one&quot; &amp;&amp; &quot;test two&quot;); // returns false
// (&quot;test one&quot; gets converted to false and returned)

(!0 || !&quot;test two&quot;); // returns true
// (0 gets converted to true and returned)
</pre>
<p>Another useful way to use the <code>!</code> operator is to use two of them &#8211; this way you always get a <code>true</code> or a <code>false</code> no matter what was given to it.</p>
<pre class="brush: jscript;">
(!!&quot;test&quot;); // returns true
//  &quot;test&quot; is converted to false, then that is converted to true

(!!&quot;&quot;); // returns false
// &quot;&quot; is converted to true, and then that true is converted to false

(!!variableThatDoesntExist); // returns false even though you're checking an undefined variable.
</pre>
<h2><a href="http://nfriedly.com/webdev">Javascript Optimization</a></h2>
<p>Need any help <a href="/webdev/javascript">optimizing the Javascript and AJAX on your website</a>? Get in touch with your friendly neighborhood <a href="http://nfriedly.com/webdev">javascript expert</a> for ideas on how to optimize your site and a free quote.</p>
]]></content:encoded>
			<wfw:commentRss>http://nfriedly.com/techblog/2009/06/advanced-javascript-operators-and-truthy-falsy/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
		<item>
		<title>How to build a spam-free contact form without captchas</title>
		<link>http://nfriedly.com/techblog/2009/06/how-to-build-a-spam-free-contact-forms-without-captchas/</link>
		<comments>http://nfriedly.com/techblog/2009/06/how-to-build-a-spam-free-contact-forms-without-captchas/#comments</comments>
		<pubDate>Sun, 07 Jun 2009 08:12:53 +0000</pubDate>
		<dc:creator>nFriedly</dc:creator>
				<category><![CDATA[Web Development]]></category>
		<category><![CDATA[antispam]]></category>
		<category><![CDATA[howto]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[php]]></category>
		<category><![CDATA[security]]></category>
		<category><![CDATA[ux]]></category>

		<guid isPermaLink="false">http://nfriedly.com/techblog/?p=23</guid>
		<description><![CDATA[Most anti-spam methods used by websites today are annoying at best. They use impossible-to-read captcha images, or they make users jump through some kind of hoop to get the email address instead of just clicking on it. This can mean lost sales and opportunities for you, because each hurdle turns away more users. This article [...]]]></description>
			<content:encoded><![CDATA[<p><img class="alignright size-thumbnail wp-image-39" title="data_security_3" src="http://nfriedly.com/techblog/wp-content/uploads/2009/06/data_security_3-150x150.jpg" alt="data_security_3" width="150" height="150" />Most anti-spam methods used by websites today are annoying at best. They use impossible-to-read captcha images, or they make users jump through some kind of hoop to get the email address instead of just clicking on it. <strong>This can mean lost sales and opportunities for you, because each hurdle turns away more users. </strong></p>
<p>This article looks at how to use some simple HTML, CSS, &amp; Javascript to protect your private information without making your guests jump through hoops.</p>
<p><span id="more-23"></span><br />
<a href="http://nfriedly.com/stuff/spam-free-contact.zip"><img class="alignleft" src="/img/application_put.png" alt="" /> Download a working copy of the contact form discussed here.</a></p>
<h2>The Goal</h2>
<p>I want users to be able to contact me simple and easy, no captchas, no math problems,  just a regular contact form, clickable email address, and everything copy-paste-able.</p>
<h2>The Problem</h2>
<p>Spammers love captcha-free forms and clickable email addresses. (And lately, copy-paste-able phone numbers.) I do not want to receive a ton of spam!</p>
<h2>The Solution</h2>
<p>With a little bit of CSS and JavaScript wizardry, we can make a simple, easy-to-use contact page that will not get you hardly any spam!</p>
<p>A downloadable example is provided at the end of the article.</p>
<h3>Part 1: The Contact Form</h3>
<p>We are going to make a standard contact form with one extra feature: an input named &#8220;url&#8221; and a note beside it that says &#8220;Don&#8217;t type anything here!&#8221;</p>
<p>The HTML:</p>
<pre class="brush: xml;">&lt;form method=&quot;post&quot; action=&quot;/submit.php&quot;&gt;
&lt;p&gt;Your name:
&lt;br /&gt;&lt;input name=&quot;name&quot; /&gt;&lt;/p&gt;

&lt;p&gt;Your email:
&lt;br /&gt;&lt;input name=&quot;email&quot; /&gt;&lt;/p&gt;

&lt;p class=&quot;antispam&quot;&gt;Leave this empty:
&lt;br /&gt;&lt;input name=&quot;url&quot; /&gt;&lt;/p&gt;

&lt;textarea name=&quot;message&quot;&gt;&lt;/textarea&gt;

&lt;input type=&quot;submit&quot; value=&quot;Send&quot; /&gt;
&lt;/form&gt;</pre>
<p>Then we use CSS to hide the input and the note.</p>
<p>The CSS:</p>
<pre class="brush: css;">.antispam { display:none;} </pre>
<p>Then we make a rule in the server that says &#8216;if the user typed anything in the &#8220;url&#8221; box, then throw it out.&#8217;</p>
<p>The PHP:</p>
<pre class="brush: php;">&lt;?php

// if the url field is empty
if(isset($_POST['url']) &amp;&amp; $_POST['url'] == ''){

	// then send the form to your email
	mail( 'you@yoursite.com', 'Contact Form', print_r($_POST,true) );
}

// otherwise, let the spammer think that they got their message through

?&gt;

&lt;h1&gt;Thanks&lt;/h1&gt;
&lt;p&gt;We'll get back to you as soon as possible&lt;/p&gt;</pre>
<p>A regular person won&#8217;t even see the box normally, and will therefore leave it blank without even thinking about it. If the CSS fails to load, they get a note explaining what to do.</p>
<p>However, when a spam bot looks at this, it sees a good spot to stick whatever spammy url they&#8217;re trying to advertise.</p>
<p>Now the php script on the server can tell who is a spammer and who isn&#8217;t. The regular people get sent to your email, the spammers get ignored!</p>
<h3>Part 2:  Click-able Email Address</h3>
<p>Spammers steal your email address by scanning through the source code of the site and grabbing anything that looks like an email address. So we&#8217;re going to make sure that there is no email address in the source code and instead generate it by JavaScript.</p>
<p>The Javascript:</p>
<pre class="brush: jscript;">var first = &quot;yourname&quot;;
var last = &quot;yoursite.com&quot;;</pre>
<p>The HTML:</p>
<pre class="brush: xml;">&lt;p&gt;My e-mail address:
&lt;script type=&quot;text/javascript&quot;&gt;
document.write('&lt;a href=&quot;mailto:'+first + '@' + last+'&quot;&gt;'+first + '@' + last+'&lt;\/a&gt;');
&lt;/script&gt;
&lt;noscript&gt;
Please enable javascript or use my &lt;a href=&quot;/contact.php&quot;&gt;contact form&lt;/a&gt;
&lt;/noscript&gt;
&lt;/p&gt;</pre>
<p>A regular user will see a regular email address and things just work. A user who happens to have javascript disabled will see an explanation and an alternative solution. And a spammer won&#8217;t see a thing!</p>
<p>This method can easily be extended to phone numbers and other personal information.</p>
<h2>Complete Examples</h2>
<p><img class="alignleft" src="/img/application_put.png" alt="" /> A complete working copy of everything mentioned in this article is available here: <a href="http://nfriedly.com/stuff/spam-free-contact.zip">http://nfriedly.com/stuff/spam-free-contact.zip</a></p>
<p>For a live demo of all of this and more, see my <a href="http://nfriedly.com/contact">contact page</a>.</p>
<p>Update: I found that there is an anti-spam plugin for WordPress that uses similar methods to the ones I describe here: <a href="http://wordpress.org/extend/plugins/nospamnx/">http://wordpress.org/extend/plugins/nospamnx/</a></p>
<h2>Does your website need help?</h2>
<p>I am an <a href="/webdev">Experienced Web Developer with a sharp eye for security</a>. I can make your site easier to use while at the same time cutting down on level of spam you receive through it.  <a href="/contact">Contact me</a> for more information and a free quote.</p>
]]></content:encoded>
			<wfw:commentRss>http://nfriedly.com/techblog/2009/06/how-to-build-a-spam-free-contact-forms-without-captchas/feed/</wfw:commentRss>
		<slash:comments>22</slash:comments>
		</item>
	</channel>
</rss>
