<?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>David Walsh :: Legendary scribbles about JavaScript, HTML5, AJAX, PHP, CSS, and ∞. &#187; JavaScript</title> <atom:link href="http://davidwalsh.name/tutorials/javascript/feed" rel="self" type="application/rss+xml" /><link>http://davidwalsh.name</link> <description>Legendary scribbles about JavaScript, HTML5, AJAX, PHP, CSS, and ∞.</description> <lastBuildDate>Thu, 02 Sep 2010 03:13:15 +0000</lastBuildDate> <language>en</language> <sy:updatePeriod>hourly</sy:updatePeriod> <sy:updateFrequency>1</sy:updateFrequency> <generator>http://wordpress.org/?v=3.0.1</generator> <item><title>Quick Tip:  Object Indexing vs. Array&#160;Collection</title><link>http://davidwalsh.name/object-array-index</link> <comments>http://davidwalsh.name/object-array-index#comments</comments> <pubDate>Thu, 26 Aug 2010 13:47:13 +0000</pubDate> <dc:creator>David Walsh</dc:creator> <category><![CDATA[JavaScript]]></category> <category><![CDATA[Optimization]]></category> <category><![CDATA[PHP]]></category><guid
isPermaLink="false">http://davidwalsh.name/?p=5052</guid> <description><![CDATA[The Setup &#38;&#160;Goal Let&#8217;s say that we have one large text document and we have a a bunch of keywords that we want to parse the document for.  We don&#8217;t care how many times times the keyword appears &#8212; we just care that it&#8217;s been used.  When we find a keyword, we need to record [...]<p><strong>Follow Me!</strong> <a
href="http://twitter.com/davidwalshblog">Twitter</a> | <a
href="http://www.facebook.com/#!/pages/David-Walsh-Blog/186644584869">Facebook</a> | <a
href="http://www.linkedin.com/in/davidjameswalsh">LinkedIn</a> | <a
href="http://mootools.net/forge/profile/davidwalsh">MooTools Forge.</a><br/><br/>Full David Walsh Blog Post: <a
href="http://davidwalsh.name/object-array-index">Quick Tip:  Object Indexing vs. Array&nbsp;Collection</a></p>Related posts:<ol><li><a
href='http://davidwalsh.name/element-collection-manipulation-shortcut-using-mootools' rel='bookmark' title='Permanent Link: Element Collection Manipulation Shortcut Using MooTools&nbsp;1.2'>Element Collection Manipulation Shortcut Using MooTools&nbsp;1.2</a></li><li><a
href='http://davidwalsh.name/implementing-array-count-method-javascript' rel='bookmark' title='Permanent Link: Implementing an Array.count() Method in&nbsp;JavaScript'>Implementing an Array.count() Method in&nbsp;JavaScript</a></li><li><a
href='http://davidwalsh.name/dojo-connect' rel='bookmark' title='Permanent Link: dojo.connect: A Powerful Object and Event&nbsp;Listener'>dojo.connect: A Powerful Object and Event&nbsp;Listener</a></li><li><a
href='http://davidwalsh.name/array-shuffling-mootools' rel='bookmark' title='Permanent Link: Implement Array Shuffling in&nbsp;MooTools'>Implement Array Shuffling in&nbsp;MooTools</a></li><li><a
href='http://davidwalsh.name/access-object-properties' rel='bookmark' title='Permanent Link: Access JavaScript Object Variable&nbsp;Properties'>Access JavaScript Object Variable&nbsp;Properties</a></li></ol>]]></description> <content:encoded><![CDATA[<h2>The Setup &amp;&nbsp;Goal</h2><p>Let&#8217;s say that we have one large text document and we have a a bunch of keywords that we want to parse the document for.  We don&#8217;t care how many times times the keyword appears &#8212; we just care that it&#8217;s been used.  When we find a keyword, we need to record that keyword been found so that we may check at a later time.</p><h2>Inefficient Method:  Array Collection and&nbsp;Search</h2><p>The first method to record that a keyword has been found is by pushing the keyword into one array:</p><pre class="js">
//Assume an array called "foundKeywords" was defined above
if(shouldSave(keyword)) {
	foundKeywords.push(keyword);
}
</pre><p>At the end of the document search, we&#8217;d end up with an array like:</p><pre class="js">
//the foundKeywords array looks like:
//['keyword1','keyword2','keyword2',...]
</pre><p>When it comes to checking this array for the existence of a given keyword, this method will prove inefficient.  Why?  Because we&#8217;d need to loop through the array and search until we found the given keyword (if ever).  Those are a lot of &#8220;wasted&#8221; or fruitless cycles, even if we break the loop when the keyword was found.  Inefficient is the only word to describe this process.</p><h2>The Efficient Method:  Object with&nbsp;Index</h2><p>The fastest method of checking a storing keywords for later reference is by object (in JavaScript) or associative array (in PHP).  Instead of adding the keyword to an array, we add the keyword as an index to a master object, giving the value as 1:</p><pre class="js">
//Assume an object {} called "foundKeywords" was defined above
if(shouldSave(keyword)) {
	foundKeywords[keyword] = 1;
}
</pre><p>Why is this faster?  No wasted cycles looking blindly through an array.  The check is quick and simple:</p><pre class="js">
if(foundKeywords[keyword]) { //FOUND!
	//do something
}
</pre><p>It&#8217;s either an index or it&#8217;s not!  In PHP, we&#8217;d save the keyword to an associative array:</p><pre class="php">
//Assume an array called "$found_keywords" was defined above
if(shouldSave($keyword)) {
	$found_keywords[$keyword] = 1;
}

//Later: checking if the keyword was there...
if($found_keywords[$keyword]) { //or array_key_exists($keyword,$found_keywords)
	//FOUND!
}
</pre><p>In a word&#8230;awesome.  Not only fast but simple!</p><p>I cannot provide a benchmark because the speed of execution depends on how large the keyword array is.  Suffice to say, for the sake of simplicity and speed, using an object with keyword index is definitely the way to go!</p><p><strong>Follow Me!</strong> <a
href="http://twitter.com/davidwalshblog">Twitter</a> | <a
href="http://www.facebook.com/#!/pages/David-Walsh-Blog/186644584869">Facebook</a> | <a
href="http://www.linkedin.com/in/davidjameswalsh">LinkedIn</a> | <a
href="http://mootools.net/forge/profile/davidwalsh">MooTools Forge.</a><br/><br/>Full David Walsh Blog Post: <a
href="http://davidwalsh.name/object-array-index">Quick Tip:  Object Indexing vs. Array&nbsp;Collection</a></p><p>Related posts:<ol><li><a
href='http://davidwalsh.name/element-collection-manipulation-shortcut-using-mootools' rel='bookmark' title='Permanent Link: Element Collection Manipulation Shortcut Using MooTools&nbsp;1.2'>Element Collection Manipulation Shortcut Using MooTools&nbsp;1.2</a></li><li><a
href='http://davidwalsh.name/implementing-array-count-method-javascript' rel='bookmark' title='Permanent Link: Implementing an Array.count() Method in&nbsp;JavaScript'>Implementing an Array.count() Method in&nbsp;JavaScript</a></li><li><a
href='http://davidwalsh.name/dojo-connect' rel='bookmark' title='Permanent Link: dojo.connect: A Powerful Object and Event&nbsp;Listener'>dojo.connect: A Powerful Object and Event&nbsp;Listener</a></li><li><a
href='http://davidwalsh.name/array-shuffling-mootools' rel='bookmark' title='Permanent Link: Implement Array Shuffling in&nbsp;MooTools'>Implement Array Shuffling in&nbsp;MooTools</a></li><li><a
href='http://davidwalsh.name/access-object-properties' rel='bookmark' title='Permanent Link: Access JavaScript Object Variable&nbsp;Properties'>Access JavaScript Object Variable&nbsp;Properties</a></li></ol></p>]]></content:encoded> <wfw:commentRss>http://davidwalsh.name/object-array-index/feed</wfw:commentRss> <slash:comments>20</slash:comments> </item> <item><title>The Beauty of&#160;dojo.require()</title><link>http://davidwalsh.name/dojo-require</link> <comments>http://davidwalsh.name/dojo-require#comments</comments> <pubDate>Fri, 06 Aug 2010 13:53:16 +0000</pubDate> <dc:creator>David Walsh</dc:creator> <category><![CDATA[Dojo]]></category> <category><![CDATA[JavaScript]]></category><guid
isPermaLink="false">http://davidwalsh.name/?p=5026</guid> <description><![CDATA[I&#8217;ve been working full time with Dojo for the past four months and one of my favorite parts of the toolkit is the dojo.require system.  The dojo.require system allows you to asynchronously request Dojo modules within the current page without needing to adjust your core Dojo build or needing to go out and download the [...]<p><strong>Follow Me!</strong> <a
href="http://twitter.com/davidwalshblog">Twitter</a> | <a
href="http://www.facebook.com/#!/pages/David-Walsh-Blog/186644584869">Facebook</a> | <a
href="http://www.linkedin.com/in/davidjameswalsh">LinkedIn</a> | <a
href="http://mootools.net/forge/profile/davidwalsh">MooTools Forge.</a><br/><br/>Full David Walsh Blog Post: <a
href="http://davidwalsh.name/dojo-require">The Beauty of&nbsp;dojo.require()</a></p>Related posts:<ol><li><a
href='http://davidwalsh.name/dojo-accordion' rel='bookmark' title='Permanent Link: Create a Simple Dojo&nbsp;Accordion'>Create a Simple Dojo&nbsp;Accordion</a></li><li><a
href='http://davidwalsh.name/dojo-chart-theme' rel='bookmark' title='Permanent Link: Dive Into Dojo Series:  Dive Into Dojo Chart&nbsp;Theming'>Dive Into Dojo Series:  Dive Into Dojo Chart&nbsp;Theming</a></li><li><a
href='http://davidwalsh.name/dojo-dijit-charting' rel='bookmark' title='Permanent Link: Dive Into Dojo Series:  Dijit and&nbsp;Charting'>Dive Into Dojo Series:  Dijit and&nbsp;Charting</a></li><li><a
href='http://davidwalsh.name/enhancing-dojo' rel='bookmark' title='Permanent Link: SitePen:  Creating and Enhancing Dojo&nbsp;Classes'>SitePen:  Creating and Enhancing Dojo&nbsp;Classes</a></li><li><a
href='http://davidwalsh.name/dojo-flickr' rel='bookmark' title='Permanent Link: Create a Dynamic Flickr Image Search with the Dojo&nbsp;Toolkit'>Create a Dynamic Flickr Image Search with the Dojo&nbsp;Toolkit</a></li></ol>]]></description> <content:encoded><![CDATA[<p>I&#8217;ve been working full time with Dojo for the past four months and one of my favorite parts of the toolkit is the dojo.require system.  The dojo.require system allows you to asynchronously request Dojo modules within the current page without needing to adjust your core Dojo build or needing to go out and download the given plugin.  dojo.require is quite comprehensive but I wanted to give you a taste of dojo.require and how it works on a very basic level.</p><h2>Step 1:  Pull Dojo From&nbsp;CDN</h2><pre class="html">
&lt;!-- pull from Google --&gt;
&lt;script src="http://ajax.googleapis.com/ajax/libs/dojo/1.5/dojo/dojo.xd.js" type="text/javascript"&gt;&lt;/script&gt;
&lt;!-- OR pull from AOL --&gt;
&lt;script src="http://o.aolcdn.com/dojo/1.5/dojo/dojo.xd.js" type="text/javascript"&gt;&lt;/script&gt;
</pre><p>You can pull the base Dojo JavaScript file from Google or AOL.  This file is very small and loads extremely fast from CDN.</p><h2>Step 2:&nbsp; dojo.require</h2><p>As mentioned earlier, the dojo.require method asynchronously requests Dojo classes from a module path.  Dojo&#8217;s smart enough to be able to request its classes from CDN even though it&#8217;s cross-domain.  You can change the module paths if you&#8217;d like but that&#8217;s out of the scope of this post.  Let&#8217;s say I want to use Dojo&#8217;s behavior class within my page.  The first step is &#8220;requiring&#8221; it:</p><pre class="js">
dojo.require('dojo.behavior');
</pre><p>That require statement fires the request for that class from the CDN.  Of course, you can&#8217;t do anything with the functionality of that class until it has loaded so you need to add a dojo.ready wrapper which doesn&#8217;t execute until all requires have loaded and the DOM is ready:</p><pre class="js">
//equivalent to jQuery's document.ready and MooTools' window.addEvent('domready')
dojo.ready(function() {
	
	//this only executes when my "requires" have loaded!
	dojo.behavior.add({
		'a.alert': {
			onclick: function(e) {
				alert('You clicked me!');
			}
		}
	})
	
});
</pre><p>Boom!  The behavior class has loaded and you&#8217;re now ready to use it!</p><p>Another cool part about dojo.require is that since each class must define the modules it requires, dependencies are automatically required when you request a class.  For example, let&#8217;s pretend I want to use a class from DojoX charting library.  I manually require once class, but Dojo&#8217;s smart enough to figure out I need many more than that:</p><pre class="js">
//I manually type this...
dojo.require('dojox.charting.widget.Chart2D');
//...but Dojo internally knows to also require more classes that help charting...
</pre><p>Firebug can tell you exactly which dependency classes get pulled from CDN:</p><p><img
src="http://davidwalsh.name/dw-content/dojo-require.png" alt="dojo.require" /></p><p>Dojo&#8217;s require system is absolutely brilliant;  it speeds up development ten-fold.  When it comes to production, however, it&#8217;s best to use Dojo&#8217;s build system to create one static JavaScript build for speed and caching purposes.  For development, however, dojo.require is a Godsend!</p><p><strong>Follow Me!</strong> <a
href="http://twitter.com/davidwalshblog">Twitter</a> | <a
href="http://www.facebook.com/#!/pages/David-Walsh-Blog/186644584869">Facebook</a> | <a
href="http://www.linkedin.com/in/davidjameswalsh">LinkedIn</a> | <a
href="http://mootools.net/forge/profile/davidwalsh">MooTools Forge.</a><br/><br/>Full David Walsh Blog Post: <a
href="http://davidwalsh.name/dojo-require">The Beauty of&nbsp;dojo.require()</a></p><p>Related posts:<ol><li><a
href='http://davidwalsh.name/dojo-accordion' rel='bookmark' title='Permanent Link: Create a Simple Dojo&nbsp;Accordion'>Create a Simple Dojo&nbsp;Accordion</a></li><li><a
href='http://davidwalsh.name/dojo-chart-theme' rel='bookmark' title='Permanent Link: Dive Into Dojo Series:  Dive Into Dojo Chart&nbsp;Theming'>Dive Into Dojo Series:  Dive Into Dojo Chart&nbsp;Theming</a></li><li><a
href='http://davidwalsh.name/dojo-dijit-charting' rel='bookmark' title='Permanent Link: Dive Into Dojo Series:  Dijit and&nbsp;Charting'>Dive Into Dojo Series:  Dijit and&nbsp;Charting</a></li><li><a
href='http://davidwalsh.name/enhancing-dojo' rel='bookmark' title='Permanent Link: SitePen:  Creating and Enhancing Dojo&nbsp;Classes'>SitePen:  Creating and Enhancing Dojo&nbsp;Classes</a></li><li><a
href='http://davidwalsh.name/dojo-flickr' rel='bookmark' title='Permanent Link: Create a Dynamic Flickr Image Search with the Dojo&nbsp;Toolkit'>Create a Dynamic Flickr Image Search with the Dojo&nbsp;Toolkit</a></li></ol></p>]]></content:encoded> <wfw:commentRss>http://davidwalsh.name/dojo-require/feed</wfw:commentRss> <slash:comments>1</slash:comments> </item> <item><title>Implement the Google AJAX Search&#160;API</title><link>http://davidwalsh.name/google-ajax-search</link> <comments>http://davidwalsh.name/google-ajax-search#comments</comments> <pubDate>Mon, 02 Aug 2010 14:04:25 +0000</pubDate> <dc:creator>David Walsh</dc:creator> <category><![CDATA[AJAX]]></category> <category><![CDATA[CSS]]></category> <category><![CDATA[Google]]></category> <category><![CDATA[JavaScript]]></category> <category><![CDATA[MooTools]]></category><guid
isPermaLink="false">http://davidwalsh.name/?p=5020</guid> <description><![CDATA[Let&#8217;s be honest&#8230;WordPress&#8217; search functionality isn&#8217;t great. Let&#8217;s be more honest&#8230;no search functionality is better than Google&#8217;s. Luckily for us, Google provides an awesome method by which we can use their search for our own site: the Google AJAX Search API. Let me show you how to implement this awesome API within your own website! [...]<p><strong>Follow Me!</strong> <a
href="http://twitter.com/davidwalshblog">Twitter</a> | <a
href="http://www.facebook.com/#!/pages/David-Walsh-Blog/186644584869">Facebook</a> | <a
href="http://www.linkedin.com/in/davidjameswalsh">LinkedIn</a> | <a
href="http://mootools.net/forge/profile/davidwalsh">MooTools Forge.</a><br/><br/>Full David Walsh Blog Post: <a
href="http://davidwalsh.name/google-ajax-search">Implement the Google AJAX Search&nbsp;API</a></p>Related posts:<ol><li><a
href='http://davidwalsh.name/search-options' rel='bookmark' title='Permanent Link: Search Type Options with&nbsp;MooTools'>Search Type Options with&nbsp;MooTools</a></li><li><a
href='http://davidwalsh.name/dojo-flickr' rel='bookmark' title='Permanent Link: Create a Dynamic Flickr Image Search with the Dojo&nbsp;Toolkit'>Create a Dynamic Flickr Image Search with the Dojo&nbsp;Toolkit</a></li><li><a
href='http://davidwalsh.name/google-load' rel='bookmark' title='Permanent Link: google.load():  Utilize Google&#8217;s AJAX Libraries&nbsp;API'>google.load():  Utilize Google&#8217;s AJAX Libraries&nbsp;API</a></li><li><a
href='http://davidwalsh.name/ajax-username-availability-checker-mootools' rel='bookmark' title='Permanent Link: AJAX Username Availability Checker Using MooTools&nbsp;1.2'>AJAX Username Availability Checker Using MooTools&nbsp;1.2</a></li><li><a
href='http://davidwalsh.name/ajax-spinner-jquery' rel='bookmark' title='Permanent Link: Form Element AJAX Spinner Attachment Using&nbsp;jQuery'>Form Element AJAX Spinner Attachment Using&nbsp;jQuery</a></li></ol>]]></description> <content:encoded><![CDATA[<a
href="http://davidwalsh.name/dw-content/google-ajax-search.php"><img
src="http://davidwalsh.name/dw-content/ajax-search-example.jpg" alt="Google AJAX Search API" /></a><p>Let&#8217;s be honest&#8230;WordPress&#8217; search functionality isn&#8217;t great.  Let&#8217;s be more honest&#8230;no search functionality is better than Google&#8217;s.  Luckily for us, Google provides an awesome method by which we can use their search for our own site:  the Google AJAX Search API.  Let me show you how to implement this awesome API within your own website!</p><div
class="actions"><a
class="demo" href="http://davidwalsh.name/dw-content/google-ajax-search.php">View Demo</a><div
class="clear"></div></div><h2>Sign&nbsp;Up!</h2><p>Google&#8217;s AJAX Search API requires that you <a
href="http://code.google.com/apis/ajaxsearch/key.html">sign up for an API key</a>.  Signing up is free and you&#8217;ll be done with the process of retrieving a key in a few minutes.</p><p><a
href="http://davidwalsh.name/dw-content/google-ajax-search.php"><img
src="http://davidwalsh.name/dw-content/ajax-search-1.jpg" alt="Google AJAX Search API Sign Up" /></a></p><p>You&#8217;ll also need to provide a domain for which they key will work for; one key per domain.</p><h2>The&nbsp;HTML</h2><pre class="html">&lt;!-- SEARCH FORM --&gt;
&lt;form action="http://www.google.com/search" method="get"&gt;
	&lt;!-- HTML5 SEARCH BOX!  --&gt;
	&lt;input type="search" id="search-box" name="q" results="5" placeholder="Search..." autocomplete="on" /&gt;
	&lt;!-- SEARCH davidwalsh.name ONLY! --&gt;
	&lt;input type="hidden" name="sitesearch" value="davidwalsh.name" /&gt;
	&lt;!-- SEARCH BUTTON --&gt;
	&lt;input id="search-submit" type="submit" value="Search" /&gt;
&lt;/form&gt;

&lt;!-- ASYNCHRONOUSLY LOAD THE AJAX SEARCH API;  MOOTOOLS TOO! --&gt;
&lt;script type="text/javascript" src="http://www.google.com/jsapi?key=MY_REALLY_REALLY_REALLY_REALLY_REALLY_REALLY_LONG_KEY"&gt;&lt;/script&gt;
&lt;script type="text/javascript"&gt;
	google.load('mootools','1.2.4');
	google.load('search','1');
&lt;/script&gt;</pre><p>You&#8217;ll want to use a &#8220;real&#8221; form so that if the user doesn&#8217;t have JavaScript, they&#8217;ll get directed to Google for their search.  Beyond that, follow the hidden input line to ensure your search will work.  You may also note that the search box has autocomplete and placeholder attributes &#8212; those are HTML5 functionality, nothing to do with Google&#8217;s AJAX Search API.</p><h2>The&nbsp;CSS</h2><pre class="css">/* results positioning */
#search-results		{ position:absolute; z-index:90; top:40px; right:10px; visibility:hidden; }
/* triangle! */
#search-results-pointer { width:0px; height:0px; border-left:20px solid transparent; border-right:20px solid transparent; border-bottom:20px solid #eee; margin-left:80%; }
/* content DIV which holds search results! */
#search-results-content { position:relative; padding:20px; background:#fff; border:3px solid #eee; width:380px; min-height:200px; -webkit-box-shadow: 5px 5px 5px rgba(0, 0, 0, 0.5) }</pre><p>The CSS above simply position the elements where I want them per my design.  I even used a CSS triangle!</p><h2>The&nbsp;JavaScript</h2><pre class="js">window.addEvent('domready',function(){

	/* search */
	var searchBox = $('search-box'), searchLoaded=false, searchFn = function() {

		/*
			We're lazyloading all of the search stuff.
			After all, why create elements, add listeners, etc. if the user never gets there?
		*/
		if(!searchLoaded) {
			searchLoaded = true; //set searchLoaded to "true"; no more loading!

			//build elements!
			var container = new Element('div',{ id: 'search-results' }).inject($('search-area'),'after');
			var wrapper = new Element('div',{
				styles: {
					position: 'relative'
				}
			}).inject(container);
			new Element('div',{ id: 'search-results-pointer' }).inject(wrapper);
			var contentContainer = new Element('div',{ id: 'search-results-content' }).inject(wrapper);
			var closer = new Element('a', {
				href: 'javascript:;',
				text: 'Close',
				styles: {
					position: 'absolute', //position the "Close" link
					bottom: 35,
					right: 20
				},
				events: {
					click: function() {
						container.fade(0);
					}
				}
			}).inject(wrapper);

			//google interaction
			var search = new google.search.WebSearch(),
				control = new google.search.SearchControl(),
				options = new google.search.DrawOptions();

			//set google options
			options.setDrawMode(google.search.SearchControl.DRAW_MODE_TABBED);
			options.setInput(searchBox);

			//set search options
			search.setUserDefinedClassSuffix('siteSearch');
			search.setSiteRestriction('davidwalsh.name');
			search.setLinkTarget(google.search.Search.LINK_TARGET_SELF);

			//set search controls
			control.addSearcher(search);
			control.draw(contentContainer,options);
			control.setNoResultsString('No results were found.');

			//add listeners to search box
			searchBox.addEvents({
				keyup: function(e) {
					if(searchBox.value &amp;&amp; searchBox.value != searchBox.get('placeholder')) {
						container.fade(0.9);
						control.execute(searchBox.value);
					}
					else {
						container.fade(0);
					}
				}
			});
			searchBox.removeEvent('focus',searchFn);
		}
	};
	searchBox.addEvent('focus',searchFn);
});</pre><p>There&#8217;s a fair amount of JavaScript above so stay with me.  The following are the steps for implementing the Google AJAX API:</p><ul><li>Create an element to house the results of the search.</li><li>Create a &#8220;Close&#8221; link which will allow the user to close the search results window.</li><li>Create our Google-given class instance:<ul><li>A Web Search (you can also create Local Search if you&#8217;d like&#8230;). <a
rel="nofollow" href="http://code.google.com/apis/ajaxsearch/documentation/reference.html#_class_GwebSearch">google.search.WebSearch options</a>.  I&#8217;ve chosen to add tabs and set the input as my search box.</li><li>A SearchControl instance. <a
rel="nofollow" href="http://code.google.com/apis/ajaxsearch/documentation/reference.html#_class_GSearchControl">google.search.SearchControl options</a>.  &#8220;siteSearch&#8221; is my suffix for results, I&#8217;ve restricted my search to the davidwalsh.name domain, and form submission will trigger results to display in the current window (instead of a new window).</li><li>A DrawOptions instance. <a
rel="nofollow" href="http://code.google.com/apis/ajaxsearch/documentation/reference.html#_class_GdrawOptions">google.search.DrawOptions options</a>.  With my DrawOptions instance, I&#8217;ve set search control, set the draw container with the options we&#8217;ve created, and I&#8217;ve decided to use Google&#8217;s default &#8220;no results&#8221; message</li></ul></li></ul><p>Once the search controls are created, it&#8217;s time to attach events to the search box to show and hide the search results container based on the contents of the search box.  That&#8217;s all!</p><p>As you can see, I&#8217;ve chosen to use the MooTools (FTW) JavaScript toolkit to create the element that houses the results, the &#8220;Close&#8221; link, and to bind events to the search box.  You could just as easily use Dojo or jQuery for element creation and even handling.</p><div
class="actions"><a
class="demo" href="http://davidwalsh.name/dw-content/google-ajax-search.php">View Demo</a><div
class="clear"></div></div><p>In all honesty, I couldn&#8217;t believe how easy it was to implement Google AJAX search.  It&#8217;s an easy want to implement search on your website, especially if you&#8217;re currently using WordPress&#8217; search.  I recommend taking the time to implement Google&#8217;s AJAX Search API &#8212; the day it takes you to get it working will save your users hours of pain!</p><p><strong>Follow Me!</strong> <a
href="http://twitter.com/davidwalshblog">Twitter</a> | <a
href="http://www.facebook.com/#!/pages/David-Walsh-Blog/186644584869">Facebook</a> | <a
href="http://www.linkedin.com/in/davidjameswalsh">LinkedIn</a> | <a
href="http://mootools.net/forge/profile/davidwalsh">MooTools Forge.</a><br/><br/>Full David Walsh Blog Post: <a
href="http://davidwalsh.name/google-ajax-search">Implement the Google AJAX Search&nbsp;API</a></p><p>Related posts:<ol><li><a
href='http://davidwalsh.name/search-options' rel='bookmark' title='Permanent Link: Search Type Options with&nbsp;MooTools'>Search Type Options with&nbsp;MooTools</a></li><li><a
href='http://davidwalsh.name/dojo-flickr' rel='bookmark' title='Permanent Link: Create a Dynamic Flickr Image Search with the Dojo&nbsp;Toolkit'>Create a Dynamic Flickr Image Search with the Dojo&nbsp;Toolkit</a></li><li><a
href='http://davidwalsh.name/google-load' rel='bookmark' title='Permanent Link: google.load():  Utilize Google&#8217;s AJAX Libraries&nbsp;API'>google.load():  Utilize Google&#8217;s AJAX Libraries&nbsp;API</a></li><li><a
href='http://davidwalsh.name/ajax-username-availability-checker-mootools' rel='bookmark' title='Permanent Link: AJAX Username Availability Checker Using MooTools&nbsp;1.2'>AJAX Username Availability Checker Using MooTools&nbsp;1.2</a></li><li><a
href='http://davidwalsh.name/ajax-spinner-jquery' rel='bookmark' title='Permanent Link: Form Element AJAX Spinner Attachment Using&nbsp;jQuery'>Form Element AJAX Spinner Attachment Using&nbsp;jQuery</a></li></ol></p>]]></content:encoded> <wfw:commentRss>http://davidwalsh.name/google-ajax-search/feed</wfw:commentRss> <slash:comments>30</slash:comments> </item> <item><title>Multiple File Upload&#160;Input</title><link>http://davidwalsh.name/multiple-file-upload</link> <comments>http://davidwalsh.name/multiple-file-upload#comments</comments> <pubDate>Mon, 19 Jul 2010 13:26:57 +0000</pubDate> <dc:creator>David Walsh</dc:creator> <category><![CDATA[JavaScript]]></category> <category><![CDATA[Markup]]></category><guid
isPermaLink="false">http://davidwalsh.name/?p=5010</guid> <description><![CDATA[More often than not, I find myself wanting to upload more than one file at a time.  Having to use multiple &#8220;file&#8221; INPUT elements is annoying, slow, and inefficient.  And if I hate them, I can&#8217;t imagine how annoyed my users would be.  Luckily Safari, Chrome, and Firefox have implemented a method by which users [...]<p><strong>Follow Me!</strong> <a
href="http://twitter.com/davidwalshblog">Twitter</a> | <a
href="http://www.facebook.com/#!/pages/David-Walsh-Blog/186644584869">Facebook</a> | <a
href="http://www.linkedin.com/in/davidjameswalsh">LinkedIn</a> | <a
href="http://mootools.net/forge/profile/davidwalsh">MooTools Forge.</a><br/><br/>Full David Walsh Blog Post: <a
href="http://davidwalsh.name/multiple-file-upload">Multiple File Upload&nbsp;Input</a></p>Related posts:<ol><li><a
href='http://davidwalsh.name/basic-file-uploading-php' rel='bookmark' title='Permanent Link: Basic File Uploading Using&nbsp;PHP'>Basic File Uploading Using&nbsp;PHP</a></li><li><a
href='http://davidwalsh.name/increase-php-file-upload-limit-using-php-ini' rel='bookmark' title='Permanent Link: Increase PHP&#8217;s File Upload Limit Using&nbsp;php.ini'>Increase PHP&#8217;s File Upload Limit Using&nbsp;php.ini</a></li><li><a
href='http://davidwalsh.name/checkbox-form-input-arrays' rel='bookmark' title='Permanent Link: Using Form Input Arrays For&nbsp;Checkboxes'>Using Form Input Arrays For&nbsp;Checkboxes</a></li><li><a
href='http://davidwalsh.name/basic-php-file-handling-create-open-read-write-append-close-delete' rel='bookmark' title='Permanent Link: Basic PHP File Handling &#8212; Create, Open, Read, Write, Append, Close, and&nbsp;Delete'>Basic PHP File Handling &#8212; Create, Open, Read, Write, Append, Close, and&nbsp;Delete</a></li><li><a
href='http://davidwalsh.name/create-zip-php' rel='bookmark' title='Permanent Link: Create a Zip File Using&nbsp;PHP'>Create a Zip File Using&nbsp;PHP</a></li></ol>]]></description> <content:encoded><![CDATA[<p><img
src="http://davidwalsh.name/dw-content/multiple-file-upload.jpg" alt="Multiple File Upload" /></p><p>More often than not, I find myself wanting to upload more than one file at a time.  Having to use multiple &#8220;file&#8221; INPUT elements is annoying, slow, and inefficient.  And if I hate them, I can&#8217;t imagine how annoyed my users would be.  Luckily Safari, Chrome, and Firefox have implemented a method by which users can upload multiple files within one INPUT element.</p><div
class="actions"><a
href="http://davidwalsh.name/dw-content/multiple-file-upload.php" class="demo">View Demo</a><div
class="clear"></div></div><h2>The&nbsp;HTML</h2><pre class="html">
&lt;!-- IMPORTANT:  FORM's enctype must be "multipart/form-data" --&gt;
&lt;form method="post" action="upload-page.php" enctype="multipart/form-data"&gt;
  &lt;input name="filesToUpload[]" id="filesToUpload" type="file" multiple="" /&gt;
&lt;/form&gt;
</pre><p>Simply adding the multiple attribute allows for multiple files to be uploaded via one INPUT element.  If you&#8217;re a stickler for validation, you&#8217;ll want to assign the multiple attribute a value of multiple.</p><h2>Listing Multiple Files with&nbsp;JavaScript</h2><pre class="js">
//get the input and UL list
var input = document.getElementById('filesToUpload');
var list = document.getElementById('fileList');

//empty list for now...
while (list.hasChildNodes()) {
	list.removeChild(ul.firstChild);
}

//for every file...
for (var x = 0; x &lt; input.files.length; x++) {
	//add to list
	var li = document.createElement('li');
	li.innerHTML = 'File ' + (x + 1) + ':  ' + input.files[x].name;
	list.append(li);
}
</pre><p>The input.files property provides an array of files for which you can check the length;  if there&#8217;s a length, you can loop through each file and access the file paths and names.</p><h2>Receiving and Handling Files with&nbsp;PHP</h2><pre class="php">
if(count($_FILES['uploads']['filesToUpload'])) {
	foreach ($_FILES['uploads']['filesToUpload'] as $file) {
	    
		//do your upload stuff here
		echo $file;
		
	}
}
</pre><p>PHP creates an array of the files uploaded with the given INPUT&#8217;s name.  This variable will always be an array within PHP.</p><div
class="actions"><a
href="http://davidwalsh.name/dw-content/multiple-file-upload.php" class="demo">View Demo</a><div
class="clear"></div></div><p>Of course, you could a Flash-based equivalent for Internet Explorer and Opera, but having to add and support another component can be taxing.  Hopefully these browsers add support for multiple file uploads soon!</p><p><strong>Follow Me!</strong> <a
href="http://twitter.com/davidwalshblog">Twitter</a> | <a
href="http://www.facebook.com/#!/pages/David-Walsh-Blog/186644584869">Facebook</a> | <a
href="http://www.linkedin.com/in/davidjameswalsh">LinkedIn</a> | <a
href="http://mootools.net/forge/profile/davidwalsh">MooTools Forge.</a><br/><br/>Full David Walsh Blog Post: <a
href="http://davidwalsh.name/multiple-file-upload">Multiple File Upload&nbsp;Input</a></p><p>Related posts:<ol><li><a
href='http://davidwalsh.name/basic-file-uploading-php' rel='bookmark' title='Permanent Link: Basic File Uploading Using&nbsp;PHP'>Basic File Uploading Using&nbsp;PHP</a></li><li><a
href='http://davidwalsh.name/increase-php-file-upload-limit-using-php-ini' rel='bookmark' title='Permanent Link: Increase PHP&#8217;s File Upload Limit Using&nbsp;php.ini'>Increase PHP&#8217;s File Upload Limit Using&nbsp;php.ini</a></li><li><a
href='http://davidwalsh.name/checkbox-form-input-arrays' rel='bookmark' title='Permanent Link: Using Form Input Arrays For&nbsp;Checkboxes'>Using Form Input Arrays For&nbsp;Checkboxes</a></li><li><a
href='http://davidwalsh.name/basic-php-file-handling-create-open-read-write-append-close-delete' rel='bookmark' title='Permanent Link: Basic PHP File Handling &#8212; Create, Open, Read, Write, Append, Close, and&nbsp;Delete'>Basic PHP File Handling &#8212; Create, Open, Read, Write, Append, Close, and&nbsp;Delete</a></li><li><a
href='http://davidwalsh.name/create-zip-php' rel='bookmark' title='Permanent Link: Create a Zip File Using&nbsp;PHP'>Create a Zip File Using&nbsp;PHP</a></li></ol></p>]]></content:encoded> <wfw:commentRss>http://davidwalsh.name/multiple-file-upload/feed</wfw:commentRss> <slash:comments>23</slash:comments> </item> <item><title>Using SCRIPT&#8217;s defer&#160;Attribute</title><link>http://davidwalsh.name/script-defer</link> <comments>http://davidwalsh.name/script-defer#comments</comments> <pubDate>Fri, 16 Jul 2010 13:18:09 +0000</pubDate> <dc:creator>David Walsh</dc:creator> <category><![CDATA[JavaScript]]></category> <category><![CDATA[Markup]]></category><guid
isPermaLink="false">http://davidwalsh.name/?p=5016</guid> <description><![CDATA[One of the seldom used attributes within the HTML tag library is the defer attribute on SCRIPT elements.  As you can probably tell by the name of the attribute, defer instructs the contents of the script tag to not execute until the page has loaded.  Take a look! Deferring Your&#160;Scripts &#60;script&#62; //do stuff (runs first) [...]<p><strong>Follow Me!</strong> <a
href="http://twitter.com/davidwalshblog">Twitter</a> | <a
href="http://www.facebook.com/#!/pages/David-Walsh-Blog/186644584869">Facebook</a> | <a
href="http://www.linkedin.com/in/davidjameswalsh">LinkedIn</a> | <a
href="http://mootools.net/forge/profile/davidwalsh">MooTools Forge.</a><br/><br/>Full David Walsh Blog Post: <a
href="http://davidwalsh.name/script-defer">Using SCRIPT&#8217;s defer&nbsp;Attribute</a></p>Related posts:<ol><li><a
href='http://davidwalsh.name/html5-placeholder' rel='bookmark' title='Permanent Link: HTML5&#8242;s placeholder&nbsp;Attribute'>HTML5&#8242;s placeholder&nbsp;Attribute</a></li><li><a
href='http://davidwalsh.name/script-style-feed' rel='bookmark' title='Permanent Link: Add the Script &#038; Style Feed to Your&nbsp;Website'>Add the Script &#038; Style Feed to Your&nbsp;Website</a></li><li><a
href='http://davidwalsh.name/script-and-style' rel='bookmark' title='Permanent Link: You Script.  You Style.  Introducing Script &#038;&nbsp;Style.'>You Script.  You Style.  Introducing Script &#038;&nbsp;Style.</a></li><li><a
href='http://davidwalsh.name/script-style-favelet' rel='bookmark' title='Permanent Link: Script &#038; Style Revamp with Submission&nbsp;Favelet'>Script &#038; Style Revamp with Submission&nbsp;Favelet</a></li><li><a
href='http://davidwalsh.name/confessions-vi' rel='bookmark' title='Permanent Link: Confessions of a Web Developer&nbsp;VI'>Confessions of a Web Developer&nbsp;VI</a></li></ol>]]></description> <content:encoded><![CDATA[<p>One of the seldom used attributes within the HTML tag library is the <span
class="attribute">defer</span> attribute on SCRIPT elements.  As you can probably tell by the name of the attribute, <span
class="attribute">defer</span> instructs the contents of the script tag to not execute until the page has loaded.  Take a look!</p><h2>Deferring Your&nbsp;Scripts</h2><pre class="html">
&lt;script&gt;
	//do stuff (runs first)
&lt;/script&gt;
&lt;script defer="defer"&gt;
	//do stuff, but defer it  (runs last)
&lt;/script&gt;
&lt;script&gt;
	//do more stuff (runs second)
&lt;/script&gt;
</pre><p>The deferred SCRIPT element&#8217;s code will execute once the rest of the page&#8217;s resources have loaded.  What does this mean?  Be sure that your document doesn&#8217;t rely on any of the code within the script during page load.  In the example above, the middle block will execute once the page has loaded even though it appears before the last block.</p><h2>More&nbsp;Details</h2><p>Olivier Rochard has written an outstanding (and more detailed) post about <a
href="http://hacks.mozilla.org/2009/06/defer/">using the defer attribute</a> on the Mozilla Hacks blog.  His post details browser support (and quality of browser support&#8230;or lack thereof), advanced examples, and tips for using the <span
class="attribute">defer</span> attribute.</p><p>What I find funny about this tag is that it seems as though most of the script I see <em>should</em> be using this attribute.</p><p><strong>Follow Me!</strong> <a
href="http://twitter.com/davidwalshblog">Twitter</a> | <a
href="http://www.facebook.com/#!/pages/David-Walsh-Blog/186644584869">Facebook</a> | <a
href="http://www.linkedin.com/in/davidjameswalsh">LinkedIn</a> | <a
href="http://mootools.net/forge/profile/davidwalsh">MooTools Forge.</a><br/><br/>Full David Walsh Blog Post: <a
href="http://davidwalsh.name/script-defer">Using SCRIPT&#8217;s defer&nbsp;Attribute</a></p><p>Related posts:<ol><li><a
href='http://davidwalsh.name/html5-placeholder' rel='bookmark' title='Permanent Link: HTML5&#8242;s placeholder&nbsp;Attribute'>HTML5&#8242;s placeholder&nbsp;Attribute</a></li><li><a
href='http://davidwalsh.name/script-style-feed' rel='bookmark' title='Permanent Link: Add the Script &#038; Style Feed to Your&nbsp;Website'>Add the Script &#038; Style Feed to Your&nbsp;Website</a></li><li><a
href='http://davidwalsh.name/script-and-style' rel='bookmark' title='Permanent Link: You Script.  You Style.  Introducing Script &#038;&nbsp;Style.'>You Script.  You Style.  Introducing Script &#038;&nbsp;Style.</a></li><li><a
href='http://davidwalsh.name/script-style-favelet' rel='bookmark' title='Permanent Link: Script &#038; Style Revamp with Submission&nbsp;Favelet'>Script &#038; Style Revamp with Submission&nbsp;Favelet</a></li><li><a
href='http://davidwalsh.name/confessions-vi' rel='bookmark' title='Permanent Link: Confessions of a Web Developer&nbsp;VI'>Confessions of a Web Developer&nbsp;VI</a></li></ol></p>]]></content:encoded> <wfw:commentRss>http://davidwalsh.name/script-defer/feed</wfw:commentRss> <slash:comments>6</slash:comments> </item> <item><title>HTML5 classList&#160;API</title><link>http://davidwalsh.name/classlist</link> <comments>http://davidwalsh.name/classlist#comments</comments> <pubDate>Tue, 13 Jul 2010 13:38:34 +0000</pubDate> <dc:creator>David Walsh</dc:creator> <category><![CDATA[CSS]]></category> <category><![CDATA[HTML5]]></category> <category><![CDATA[JavaScript]]></category><guid
isPermaLink="false">http://davidwalsh.name/?p=5009</guid> <description><![CDATA[Having thrust myself into the world of JavaScript and JavaScript Libraries, I&#8217;ve often wondered: When are browser vendors going to see the helper methods/libraries created by the JavaScript toolkits and implement these functionalities natively within the browser? I realize that standards are important and browser vendors can&#8217;t afford to half-ass these implementations but I do [...]<p><strong>Follow Me!</strong> <a
href="http://twitter.com/davidwalshblog">Twitter</a> | <a
href="http://www.facebook.com/#!/pages/David-Walsh-Blog/186644584869">Facebook</a> | <a
href="http://www.linkedin.com/in/davidjameswalsh">LinkedIn</a> | <a
href="http://mootools.net/forge/profile/davidwalsh">MooTools Forge.</a><br/><br/>Full David Walsh Blog Post: <a
href="http://davidwalsh.name/classlist">HTML5 classList&nbsp;API</a></p>Related posts:<ol><li><a
href='http://davidwalsh.name/html5-storage' rel='bookmark' title='Permanent Link: Using HTML5 Web&nbsp;Storage'>Using HTML5 Web&nbsp;Storage</a></li><li><a
href='http://davidwalsh.name/html5-prefetch' rel='bookmark' title='Permanent Link: HTML5 Link&nbsp;Prefetching'>HTML5 Link&nbsp;Prefetching</a></li><li><a
href='http://davidwalsh.name/html5-elements-links' rel='bookmark' title='Permanent Link: HTML5:  Wrap Block-Level Elements with&nbsp;A&#8217;s'>HTML5:  Wrap Block-Level Elements with&nbsp;A&#8217;s</a></li><li><a
href='http://davidwalsh.name/quickboxes-dojo' rel='bookmark' title='Permanent Link: QuickBoxes for&nbsp;Dojo'>QuickBoxes for&nbsp;Dojo</a></li><li><a
href='http://davidwalsh.name/set-wordpress-blog-trackback-toggling' rel='bookmark' title='Permanent Link: Set Up Your WordPress Blog To Allow Trackback&nbsp;Toggling'>Set Up Your WordPress Blog To Allow Trackback&nbsp;Toggling</a></li></ol>]]></description> <content:encoded><![CDATA[<p>Having thrust myself into the world of JavaScript and JavaScript Libraries, I&#8217;ve often wondered: <strong>When are browser vendors going to see the helper methods/libraries created by the JavaScript toolkits and implement these functionalities natively within the browser?</strong> I realize that standards are important and browser vendors can&#8217;t afford to half-ass these implementations but I do believe they could be&#8230;expedited.  The good news is that one of these functionalities has been add to the HTML5 API; <span
class="function">classList</span>.</p><p>The <span
class="function">classList</span> object, added to all nodes within the DOM, provides developers methods by which to add, remove, and toggle CSS classes on a node.  <span
class="function">classList</span> also allows developers to check if a CSS class has been assigned to a given node.</p><h2>node.classList</h2><pre class="js">
{
	length: {number}, /* # of class on this element */
	add: function() { [native code] },
	contains: function() { [native code] },
	item: function() { [native code] }, /* by index */
	remove: function() { [native code] },
	toggle: function() { [native code] }
}
</pre><p>node.classList, as you can see, is a small but useful collection of methods.</p><h2>Adding a CSS&nbsp;Class</h2><pre class="js">
myDiv.classList.add('myCssClass');
</pre><br
/><h2>Removing a CSS&nbsp;Class</h2><pre class="js">
myDiv.classList.remove('myCssClass');
</pre><br
/><h2>Toggling a CSS&nbsp;Class</h2><pre class="js">
myDiv.classList.toggle('myCssClass'); //now it's added
myDiv.classList.toggle('myCssClass'); //now it's removed
</pre><p><em>Note:  If toggle is called and the element does not have the provided CSS class, the class is added.</em></p><h2>Contains CSS Class&nbsp;Check</h2><pre class="css">
myDiv.classList.contains('myCssClass'); //returns true or false
</pre><br
/><p>Mozilla Firefox is the only browser that currently supports the <span
class="function">classList</span> API.  As more browsers add classList support, look for the JavaScript libraries to include <span
class="function">classList</span> checks instead of parsing an element&#8217;s class attribute!</p><p><strong>Follow Me!</strong> <a
href="http://twitter.com/davidwalshblog">Twitter</a> | <a
href="http://www.facebook.com/#!/pages/David-Walsh-Blog/186644584869">Facebook</a> | <a
href="http://www.linkedin.com/in/davidjameswalsh">LinkedIn</a> | <a
href="http://mootools.net/forge/profile/davidwalsh">MooTools Forge.</a><br/><br/>Full David Walsh Blog Post: <a
href="http://davidwalsh.name/classlist">HTML5 classList&nbsp;API</a></p><p>Related posts:<ol><li><a
href='http://davidwalsh.name/html5-storage' rel='bookmark' title='Permanent Link: Using HTML5 Web&nbsp;Storage'>Using HTML5 Web&nbsp;Storage</a></li><li><a
href='http://davidwalsh.name/html5-prefetch' rel='bookmark' title='Permanent Link: HTML5 Link&nbsp;Prefetching'>HTML5 Link&nbsp;Prefetching</a></li><li><a
href='http://davidwalsh.name/html5-elements-links' rel='bookmark' title='Permanent Link: HTML5:  Wrap Block-Level Elements with&nbsp;A&#8217;s'>HTML5:  Wrap Block-Level Elements with&nbsp;A&#8217;s</a></li><li><a
href='http://davidwalsh.name/quickboxes-dojo' rel='bookmark' title='Permanent Link: QuickBoxes for&nbsp;Dojo'>QuickBoxes for&nbsp;Dojo</a></li><li><a
href='http://davidwalsh.name/set-wordpress-blog-trackback-toggling' rel='bookmark' title='Permanent Link: Set Up Your WordPress Blog To Allow Trackback&nbsp;Toggling'>Set Up Your WordPress Blog To Allow Trackback&nbsp;Toggling</a></li></ol></p>]]></content:encoded> <wfw:commentRss>http://davidwalsh.name/classlist/feed</wfw:commentRss> <slash:comments>7</slash:comments> </item> <item><title>Google Font&#160;API</title><link>http://davidwalsh.name/google-fonts-api</link> <comments>http://davidwalsh.name/google-fonts-api#comments</comments> <pubDate>Tue, 06 Jul 2010 13:57:10 +0000</pubDate> <dc:creator>David Walsh</dc:creator> <category><![CDATA[CSS]]></category> <category><![CDATA[Google]]></category> <category><![CDATA[JavaScript]]></category><guid
isPermaLink="false">http://davidwalsh.name/?p=5005</guid> <description><![CDATA[Google recently debuted a new web service called the Font API.  Google&#8217;s Font API provides developers a means by which they may quickly and painlessly add custom fonts to their website.  Let&#8217;s take a quick look at the ways by which the Google Font API can be used. View Demo Font Request&#160;Format Many of the [...]<p><strong>Follow Me!</strong> <a
href="http://twitter.com/davidwalshblog">Twitter</a> | <a
href="http://www.facebook.com/#!/pages/David-Walsh-Blog/186644584869">Facebook</a> | <a
href="http://www.linkedin.com/in/davidjameswalsh">LinkedIn</a> | <a
href="http://mootools.net/forge/profile/davidwalsh">MooTools Forge.</a><br/><br/>Full David Walsh Blog Post: <a
href="http://davidwalsh.name/google-fonts-api">Google Font&nbsp;API</a></p>Related posts:<ol><li><a
href='http://davidwalsh.name/cufon' rel='bookmark' title='Permanent Link: Font Replacement Using&nbsp;Cufón'>Font Replacement Using&nbsp;Cufón</a></li><li><a
href='http://davidwalsh.name/css-wishlist-css-variables-fonts' rel='bookmark' title='Permanent Link: My CSS&nbsp;Wishlist'>My CSS&nbsp;Wishlist</a></li><li><a
href='http://davidwalsh.name/font-check-plugin' rel='bookmark' title='Permanent Link: MooTools FontChecker&nbsp;Plugin'>MooTools FontChecker&nbsp;Plugin</a></li><li><a
href='http://davidwalsh.name/combine-css-media-styles-file' rel='bookmark' title='Permanent Link: Combine Your CSS Media Styles Into One&nbsp;File'>Combine Your CSS Media Styles Into One&nbsp;File</a></li><li><a
href='http://davidwalsh.name/secure-ssl-google-analytics' rel='bookmark' title='Permanent Link: Secure (SSL) Google&nbsp;Analytics'>Secure (SSL) Google&nbsp;Analytics</a></li></ol>]]></description> <content:encoded><![CDATA[<p>Google recently debuted a new web service called the Font API.  <a
href="http://code.google.com/apis/webfonts/" rel="nofollow">Google&#8217;s Font API</a> provides developers a means by which they may quickly and painlessly add custom fonts to their website.  Let&#8217;s take a quick look at the ways by which the Google Font API can be used.</p><div
class="actions"><a
href="http://davidwalsh.name/dw-content/google-font-api.php" class="demo">View Demo</a><div
class="clear"></div></div><h2>Font Request&nbsp;Format</h2><p>Many of the fonts within Google&#8217;s font archive are available not only in standard format but also in Italic, Bold, and Italic Bold.  The format for requesting a given font variant is:</p><pre class="css">
{font}:{variant1},{variant2}
</pre><p>Here are a few examples of requesting each variant:</p><pre class="css">
Cantarell
Cantarell:bold
Cantarell:italic
Cantarell:bolditalic
</pre><p>Now let&#8217;s see how we can include special fonts in our page and use these them.</p><h2>The CSS Stylesheet&nbsp;Method</h2><pre class="html">
&lt;link rel="stylesheet" type="text/css" href="http://fonts.googleapis.com/css?family=Cantarell" /&gt;
</pre><p>The stylesheet gets included into the page like any other stylesheet would be.  A query string with a family parameter is appended to the stylesheet&#8217;s URL containing the font(s) to be loaded.  Multiple fonts can be requested with the use of the &#8220;|&#8221; (pipe) character.  A few examples:</p><pre class="html">
&lt;link rel="stylesheet" type="text/css" href="http://fonts.googleapis.com/css?family=Vollkorn" /&gt;
&lt;link rel="stylesheet" type="text/css" href="http://fonts.googleapis.com/css?family=Vollkorn:bold" /&gt;
&lt;link rel="stylesheet" type="text/css" href="http://fonts.googleapis.com/css?family=Vollkorn|IM+Fell+Great+Primer" /&gt;
</pre><p>Take a moment to examine the stylesheet from Google:</p><pre class="css">
@font-face {
	font-family: 'IM Fell Great Primer';
	font-style: normal;
	font-weight: normal;
	src: local('IM Fell Great Primer'), url('http://themes.googleusercontent.com/font?kit=AL8ALGNthei20f9Cu3e93rvDyRCRMn38Ifm6ee4fjno') format('truetype');
}
@font-face {
	font-family: 'Vollkorn';
	font-style: normal;
	font-weight: normal;
	src: local('Vollkorn'), url('http://themes.googleusercontent.com/font?kit=_3YMy3W41J9lZ9YHm0HVxA') format('truetype');
}
</pre><p>The @font-face method of font embedding is Google&#8217;s chosen method.  Using the font is as simple as using a system font:</p><pre class="css">
.mySpecialFontClass	{ font-family:'Vollkorn', serif; }
</pre><p>You may also embed the font within the &#8220;style&#8221; attribute of a given element:</p><pre class="html">
&lt;p style="font-family:'Vollkorn';"&gt;Lorem ipsum....&lt;/p&gt;
</pre><p>I t doesn&#8217;t get more painless than that.</p><h2>The Simple JavaScript&nbsp;Method</h2><p>Google also provides a simple JavaScript method for including custom fonts within a page.  This method requires including the JSAPI JavaScript file and a very small snippet of JavaScript:</p><pre class="html">
&lt;script type="text/javascript" src="http://www.google.com/jsapi"&gt;&lt;/script&gt;
&lt;script type="text/javascript"&gt;
	google.load('webfont','1');
	google.setOnLoadCallback(function() {
		WebFont.load({
			google: {
				families: ['Tangerine','Cantarell']
			}
		});
	});
&lt;/script&gt;
</pre><p>Selecting font variants is done with a simple &#8220;:&#8221; delimiter between the font and the variant:</p><pre class="js">
WebFont.load({
	google: {
		families: ['Tangerine:bold']
	}
});
</pre><p>You may also load multiple fonts within the families array:</p><pre class="js">
WebFont.load({
	google: {
		families: ['Tangerine:bold','Cantarell','Lobster']
	}
});
</pre><p>Simple, no?  If it&#8217;s too simple for you, there&#8217;s more advanced method.</p><h2>The Advanced JavaScript&nbsp;Method</h2><p>The advanced JavaScript method employes an async JavaScript method paired with a WebFontConfig object.  The advanced method also adds callbacks for font requests:</p><pre class="js">
WebFontConfig = {
	google: {
		families: [ 'Tangerine', 'Cantarell' ]
	},
	/* Called when all the specified web-font provider modules (google, typekit, and/or custom) have reported that they have started loading fonts. */
	loading: function() {
		// do something
	},
	/* Called when each requested web font has started loading. The fontFamily parameter is the name of the font family, and fontDescription represents the style and weight of the font. */
	fontloading: function(fontFamily, fontDescription) {
		// do something
	},
	/* Called when each requested web font has finished loading. The fontFamily parameter is the name of the font family, and fontDescription represents the style and weight of the font. */
	fontactive: function(fontFamily, fontDescription) {
		// do something
	},
	/* Called if a requested web font failed to load. The fontFamily parameter is the name of the font family, and fontDescription represents the style and weight of the font. */
	fontinactive: function(fontFamily, fontDescription) {
		// do something
	},
	/* Called when all of the web fonts have either finished loading or failed to load, as long as at least one loaded successfully. */
	active: function() {
		// do something
	},
	/* Called if the browser does not support web fonts or if none of the fonts could be loaded. */
	inactive: function() {
		// do something
	}
};

/* async! */
(function() {
var wf = document.createElement('script');
wf.src = ('https:' == document.location.protocol ? 'https' : 'http') + '://ajax.googleapis.com/ajax/libs/webfont/1/webfont.js';
wf.type = 'text/javascript';
wf.async = 'true';
var s = document.getElementsByTagName('script')[0];
s.parentNode.insertBefore(wf, s);
})();
</pre><p>If you&#8217;re like me, you loooooooove JavaScript callbacks.  You would use this method if you wanted to &#8220;preload&#8221; fonts before assigning fonts to specific elements.  What&#8217;s also great about this method is that Google uses &#8220;active&#8221; and &#8220;inactive&#8221; CSS class representations on the HTML element to designate what an element&#8217;s settings should be before and after a font has been loaded:</p><pre class="css">
.wf-inactive p { /* Show paragraphs in serif font until fonts have loaded. */
	font-family: serif
}
.wf-active p { /* Show paragraphs in Tangerine when the fonts have loaded. */
	font-family: 'Tangerine', serif
}
.wf-inactive h1 { /* Show heading in serif font until fonts have loaded. */
	font-family: serif;
	font-size: 16px
}
.wf-active h1 { /* Show heading in Cantarell when the fonts have loaded. */
	font-family: 'Cantarell', serif;
	font-size: 16px
}
</pre><p>Unfortunately you need to add these directives to you stylesheet;  I prefer not to.</p><div
class="actions"><a
href="http://davidwalsh.name/dw-content/google-font-api.php" class="demo">View Demo</a><div
class="clear"></div></div><p>What do you think of Google latest JavaScript API?  On one side I see the Font API as extremely useful but the other side of me sees Google trying to grab a stronger hold of the Web;  trying to make websites dependent upon them.  What are your thoughts?</p><p><strong>Follow Me!</strong> <a
href="http://twitter.com/davidwalshblog">Twitter</a> | <a
href="http://www.facebook.com/#!/pages/David-Walsh-Blog/186644584869">Facebook</a> | <a
href="http://www.linkedin.com/in/davidjameswalsh">LinkedIn</a> | <a
href="http://mootools.net/forge/profile/davidwalsh">MooTools Forge.</a><br/><br/>Full David Walsh Blog Post: <a
href="http://davidwalsh.name/google-fonts-api">Google Font&nbsp;API</a></p><p>Related posts:<ol><li><a
href='http://davidwalsh.name/cufon' rel='bookmark' title='Permanent Link: Font Replacement Using&nbsp;Cufón'>Font Replacement Using&nbsp;Cufón</a></li><li><a
href='http://davidwalsh.name/css-wishlist-css-variables-fonts' rel='bookmark' title='Permanent Link: My CSS&nbsp;Wishlist'>My CSS&nbsp;Wishlist</a></li><li><a
href='http://davidwalsh.name/font-check-plugin' rel='bookmark' title='Permanent Link: MooTools FontChecker&nbsp;Plugin'>MooTools FontChecker&nbsp;Plugin</a></li><li><a
href='http://davidwalsh.name/combine-css-media-styles-file' rel='bookmark' title='Permanent Link: Combine Your CSS Media Styles Into One&nbsp;File'>Combine Your CSS Media Styles Into One&nbsp;File</a></li><li><a
href='http://davidwalsh.name/secure-ssl-google-analytics' rel='bookmark' title='Permanent Link: Secure (SSL) Google&nbsp;Analytics'>Secure (SSL) Google&nbsp;Analytics</a></li></ol></p>]]></content:encoded> <wfw:commentRss>http://davidwalsh.name/google-fonts-api/feed</wfw:commentRss> <slash:comments>9</slash:comments> </item> <item><title>Using Firefox&#8217;s Geolocation&#160;API</title><link>http://davidwalsh.name/geolocation-api</link> <comments>http://davidwalsh.name/geolocation-api#comments</comments> <pubDate>Mon, 28 Jun 2010 13:35:21 +0000</pubDate> <dc:creator>David Walsh</dc:creator> <category><![CDATA[Browsers]]></category> <category><![CDATA[JavaScript]]></category><guid
isPermaLink="false">http://davidwalsh.name/?p=4997</guid> <description><![CDATA[One interesting aspect of web development is Geolocation; where is your user viewing your website from? You can base your language locale on that data or show certain products in your store based on the user&#8217;s location. Let&#8217;s examine how you can use Geolocation within Firefox to get location details down to the street! View [...]<p><strong>Follow Me!</strong> <a
href="http://twitter.com/davidwalshblog">Twitter</a> | <a
href="http://www.facebook.com/#!/pages/David-Walsh-Blog/186644584869">Facebook</a> | <a
href="http://www.linkedin.com/in/davidjameswalsh">LinkedIn</a> | <a
href="http://mootools.net/forge/profile/davidwalsh">MooTools Forge.</a><br/><br/>Full David Walsh Blog Post: <a
href="http://davidwalsh.name/geolocation-api">Using Firefox&#8217;s Geolocation&nbsp;API</a></p>Related posts:<ol><li><a
href='http://davidwalsh.name/favorite-link-create-bookmark-link' rel='bookmark' title='Permanent Link: &#8220;Favorite&#8221; Link &#8212; How To Create a Bookmark&nbsp;Link'>&#8220;Favorite&#8221; Link &#8212; How To Create a Bookmark&nbsp;Link</a></li><li><a
href='http://davidwalsh.name/firefox-plugins' rel='bookmark' title='Permanent Link: My Firefox&nbsp;Plugins'>My Firefox&nbsp;Plugins</a></li><li><a
href='http://davidwalsh.name/detect-iphone' rel='bookmark' title='Permanent Link: iPhone &#038; iPod Detection Using&nbsp;JavaScript'>iPhone &#038; iPod Detection Using&nbsp;JavaScript</a></li><li><a
href='http://davidwalsh.name/detecting-google-chrome-javascript' rel='bookmark' title='Permanent Link: Detecting Google Chrome Using&nbsp;JavaScript'>Detecting Google Chrome Using&nbsp;JavaScript</a></li><li><a
href='http://davidwalsh.name/jquery-favelet-documentation' rel='bookmark' title='Permanent Link: jQuery Code Documentation&nbsp;Favelet'>jQuery Code Documentation&nbsp;Favelet</a></li></ol>]]></description> <content:encoded><![CDATA[<a
href="http://davidwalsh.name/dw-content/geolocation.php"><img
src="http://davidwalsh.name/dw-content/firefox-256.png" alt="Mozilla Firefox Geolocation" class="image" /></a><p>One interesting aspect of web development is Geolocation;  where is your user viewing your website from?  You can base your language locale on that data or show certain products in your store based on the user&#8217;s location.  Let&#8217;s examine how you can use <a
href="https://developer.mozilla.org/en/using_geolocation" rel="nofollow">Geolocation within Firefox</a> to get location details down to the street!</p><div
class="actions"><a
href="http://davidwalsh.name/dw-content/geolocation.php" class="demo">View Demo</a><div
class="clear"></div></div><h2>Detecting Browser Geolocation&nbsp;Capabilities</h2><pre class="js">
if(navigator.geolocation) {
	//w00t!
}
else {
	alert('No soup for you!  Your browser does not support this feature');
}
</pre><p>They key to detecting Geolocation within your browser is the <span
class="function">navigator.geolocation</span> object.</p><h2>Querying For Geolocation&nbsp;Information</h2><pre class="js">
if(navigator.geolocation) {
	navigator.geolocation.getCurrentPosition(function(position) {
		alert('Your lat-long is: ' + position.coords.latitude + ' / ' + position.coords.longitude);
		alert('You live in ' + position.address.city + ', ' + position.address.state)
	});
}
</pre><p>The <span
class="function">navigator.geolocation.getCurrentPosition</span> method is the driving force behind retrieving location details.  Once you call this method (providing it a function which will execute if your request is successful), the browser will ask the user if they will allow you to retrieve their location information:</p><a
href="http://davidwalsh.name/dw-content/geolocation.php"><img
src="http://davidwalsh.name/dw-content/geolocationbar.jpg" alt="Mozilla Firefox Geolocation Permissions" class="image" /></a><p>When the user allows the website to retrieve their location information, Firefox fetches the information, providing you a position object with two very useful attributes: <span
class="function">position.coords</span> and <span
class="function">position.address</span>. <span
class="function">position.coords</span> gives you latitude and longitude while position.address gives you streetNumber, street, premises, city, county, region, country, countryCode, and postalCode.  Firefox may even take a picture of your user through his/her window soon. <em>(Editor&#8217;s note:  I completely made that up)</em></p><div
class="actions"><a
href="http://davidwalsh.name/dw-content/geolocation.php" class="demo">View Demo</a><div
class="clear"></div></div><p>Of course most of this functionality is only available within Firefox. <a
href="http://developer.apple.com/safari/library/documentation/AppleApplications/Reference/SafariWebContent/GettingGeographicalLocations/GettingGeographicalLocations.html" rel="nofollow">Safari</a> will retrieve the user&#8217;s latitude and longitude but that&#8217;s the extent of WebKit&#8217;s support.  I look forward to bigger and better things from the W3C&#8217;s Geolocation API in the future!</p><p><strong>Follow Me!</strong> <a
href="http://twitter.com/davidwalshblog">Twitter</a> | <a
href="http://www.facebook.com/#!/pages/David-Walsh-Blog/186644584869">Facebook</a> | <a
href="http://www.linkedin.com/in/davidjameswalsh">LinkedIn</a> | <a
href="http://mootools.net/forge/profile/davidwalsh">MooTools Forge.</a><br/><br/>Full David Walsh Blog Post: <a
href="http://davidwalsh.name/geolocation-api">Using Firefox&#8217;s Geolocation&nbsp;API</a></p><p>Related posts:<ol><li><a
href='http://davidwalsh.name/favorite-link-create-bookmark-link' rel='bookmark' title='Permanent Link: &#8220;Favorite&#8221; Link &#8212; How To Create a Bookmark&nbsp;Link'>&#8220;Favorite&#8221; Link &#8212; How To Create a Bookmark&nbsp;Link</a></li><li><a
href='http://davidwalsh.name/firefox-plugins' rel='bookmark' title='Permanent Link: My Firefox&nbsp;Plugins'>My Firefox&nbsp;Plugins</a></li><li><a
href='http://davidwalsh.name/detect-iphone' rel='bookmark' title='Permanent Link: iPhone &#038; iPod Detection Using&nbsp;JavaScript'>iPhone &#038; iPod Detection Using&nbsp;JavaScript</a></li><li><a
href='http://davidwalsh.name/detecting-google-chrome-javascript' rel='bookmark' title='Permanent Link: Detecting Google Chrome Using&nbsp;JavaScript'>Detecting Google Chrome Using&nbsp;JavaScript</a></li><li><a
href='http://davidwalsh.name/jquery-favelet-documentation' rel='bookmark' title='Permanent Link: jQuery Code Documentation&nbsp;Favelet'>jQuery Code Documentation&nbsp;Favelet</a></li></ol></p>]]></content:encoded> <wfw:commentRss>http://davidwalsh.name/geolocation-api/feed</wfw:commentRss> <slash:comments>8</slash:comments> </item> <item><title>Using HTML5 Web&#160;Storage</title><link>http://davidwalsh.name/html5-storage</link> <comments>http://davidwalsh.name/html5-storage#comments</comments> <pubDate>Mon, 28 Jun 2010 13:35:19 +0000</pubDate> <dc:creator>David Walsh</dc:creator> <category><![CDATA[HTML5]]></category> <category><![CDATA[JavaScript]]></category><guid
isPermaLink="false">http://davidwalsh.name/?p=4998</guid> <description><![CDATA[HTML5 is the biggest buzz word in web development today.  The new features promised by HTML5 will be a huge boost to web developers looking to stop rigging up ways to make their websites better, faster, and more flexible.  One feature that&#8217;s caught my eye is HTML5&#8242;s Web Storage.  Web Storage provides a client-side method [...]<p><strong>Follow Me!</strong> <a
href="http://twitter.com/davidwalshblog">Twitter</a> | <a
href="http://www.facebook.com/#!/pages/David-Walsh-Blog/186644584869">Facebook</a> | <a
href="http://www.linkedin.com/in/davidjameswalsh">LinkedIn</a> | <a
href="http://mootools.net/forge/profile/davidwalsh">MooTools Forge.</a><br/><br/>Full David Walsh Blog Post: <a
href="http://davidwalsh.name/html5-storage">Using HTML5 Web&nbsp;Storage</a></p>Related posts:<ol><li><a
href='http://davidwalsh.name/classlist' rel='bookmark' title='Permanent Link: HTML5 classList&nbsp;API'>HTML5 classList&nbsp;API</a></li><li><a
href='http://davidwalsh.name/html5-prefetch' rel='bookmark' title='Permanent Link: HTML5 Link&nbsp;Prefetching'>HTML5 Link&nbsp;Prefetching</a></li><li><a
href='http://davidwalsh.name/html5-elements-links' rel='bookmark' title='Permanent Link: HTML5:  Wrap Block-Level Elements with&nbsp;A&#8217;s'>HTML5:  Wrap Block-Level Elements with&nbsp;A&#8217;s</a></li><li><a
href='http://davidwalsh.name/html5-placeholder' rel='bookmark' title='Permanent Link: HTML5&#8242;s placeholder&nbsp;Attribute'>HTML5&#8242;s placeholder&nbsp;Attribute</a></li><li><a
href='http://davidwalsh.name/geolocation-api' rel='bookmark' title='Permanent Link: Using Firefox&#8217;s Geolocation&nbsp;API'>Using Firefox&#8217;s Geolocation&nbsp;API</a></li></ol>]]></description> <content:encoded><![CDATA[<p>HTML5 is the biggest buzz word in web development today.  The new features promised by HTML5 will be a huge boost to web developers looking to stop rigging up ways to make their websites better, faster, and more flexible.  One feature that&#8217;s caught my eye is <a
href="http://dev.w3.org/html5/webstorage/" rel="nofollow">HTML5&#8242;s Web Storage</a>.  Web Storage provides a client-side method for saving session information.  Take a look at how Web Storage works!</p><h2>Simple Web Storage&nbsp;Facts</h2><ul><li>Values can be any data type supported by the structured clone algorithm.</li><li>User agents should not expire data from a browsing context&#8217;s session storage areas, but may do so when the user requests that such data be deleted, or when the UA detects that it has limited storage space, or for security reasons.</li><li>Storage items are available on the entire domain.</li></ul><h2>HTML5 Web Storage&nbsp;Methods</h2><ul><li><strong>setItem(key,value):</strong> adds a key/value pair to the <span
class="function">sessionStorage</span> object.</li><li><strong>getItem(key):</strong> retrieves the value for a given key.</li><li><strong>clear():</strong> removes all key/value pairs for the <span
class="function">sessionStorage</span> object.</li><li><strong>removeItem(key):</strong> removes a key/value pair from the <span
class="function">sessionStorage</span> object.</li><li><strong>key(n):</strong  >retrieves the value for key[n].</li></ul><h2>Setting a&nbsp;Key/Value</h2><p>There are two different methods for setting information into <span
class="function">sessionStorage</span>:</p><pre class="js">
sessionStorage.setItem('someKey','someValue');
</pre><p>&#8230;or you could just use the shortcut method:</p><pre class="js">
sessionStorage.someKey = 'someValue';
</pre><h2>Getting a&nbsp;Value</h2><p>There are two methods to retrieve a key/value pair as well:</p><pre class="js">
sessionStorage.getItem('someKey'); //returns 'someValue'
</pre><p>&#8230;or simply reference the <span
class="function">sessionStorage</span> object:</p><pre class="js">
sessionStorage.someKey; //returns 'someValue'
</pre><h2>Removing a&nbsp;Key/Value</h2><pre class="js">
sessionStorage.removeItem('someKey'); //returns 'undefined' for someKey
</pre><p>All you need to do is provide the key to the <span
class="function">removeItem</span> method.</p><h2>Clearing&nbsp;Storage</h2><pre class="js">
sessionStorage.clear(); //everything gone!
</pre><p>A simple clear call &#8212; that&#8217;s it.</p><h2>(Very) Basic Web Storage Usage&nbsp;Example</h2><pre class="html">
&lt;a href="javascript:;" onClick="if(sessionStorage &amp;&amp; sessionStorage.getItem('name')) { alert('Come back soon, ' + sessionStorage.getItem('name')); }"&gt;Sign Out&lt;/a&gt;
</pre><p>When the user clicks the sign out link, we ask them to come back soon!</p><h2>Browser&nbsp;Support&#8230;Ugh</h2><p>Like every other cool feature available today, browser support is a concern.  Internet Explorer did not support Web Storage until IE8 so you will need to create your own sessionStorage object/class (maybe with <a
href="http://davidwalsh.name/introducing-mootools-cache">MooTools</a> or Dojo?) if you want to support earlier IE browsers.</p><p>HTML5 Web Storage is very simple but very intriguing.  Since HTML5 Web Storage requires JavaScript, you wont want to use this for any mission critical application unless you want to force users to use a browser that supports the feature.</p><p>What are your thoughts about HTML5 Web Storage?  Have you used this for any applications yet?</p><p><strong>Follow Me!</strong> <a
href="http://twitter.com/davidwalshblog">Twitter</a> | <a
href="http://www.facebook.com/#!/pages/David-Walsh-Blog/186644584869">Facebook</a> | <a
href="http://www.linkedin.com/in/davidjameswalsh">LinkedIn</a> | <a
href="http://mootools.net/forge/profile/davidwalsh">MooTools Forge.</a><br/><br/>Full David Walsh Blog Post: <a
href="http://davidwalsh.name/html5-storage">Using HTML5 Web&nbsp;Storage</a></p><p>Related posts:<ol><li><a
href='http://davidwalsh.name/classlist' rel='bookmark' title='Permanent Link: HTML5 classList&nbsp;API'>HTML5 classList&nbsp;API</a></li><li><a
href='http://davidwalsh.name/html5-prefetch' rel='bookmark' title='Permanent Link: HTML5 Link&nbsp;Prefetching'>HTML5 Link&nbsp;Prefetching</a></li><li><a
href='http://davidwalsh.name/html5-elements-links' rel='bookmark' title='Permanent Link: HTML5:  Wrap Block-Level Elements with&nbsp;A&#8217;s'>HTML5:  Wrap Block-Level Elements with&nbsp;A&#8217;s</a></li><li><a
href='http://davidwalsh.name/html5-placeholder' rel='bookmark' title='Permanent Link: HTML5&#8242;s placeholder&nbsp;Attribute'>HTML5&#8242;s placeholder&nbsp;Attribute</a></li><li><a
href='http://davidwalsh.name/geolocation-api' rel='bookmark' title='Permanent Link: Using Firefox&#8217;s Geolocation&nbsp;API'>Using Firefox&#8217;s Geolocation&nbsp;API</a></li></ol></p>]]></content:encoded> <wfw:commentRss>http://davidwalsh.name/html5-storage/feed</wfw:commentRss> <slash:comments>10</slash:comments> </item> <item><title>dojo.connect: A Powerful Object and Event&#160;Listener</title><link>http://davidwalsh.name/dojo-connect</link> <comments>http://davidwalsh.name/dojo-connect#comments</comments> <pubDate>Wed, 23 Jun 2010 00:12:33 +0000</pubDate> <dc:creator>David Walsh</dc:creator> <category><![CDATA[Dojo]]></category> <category><![CDATA[JavaScript]]></category><guid
isPermaLink="false">http://davidwalsh.name/?p=4994</guid> <description><![CDATA[One of the pieces of the Dojo Toolkit I&#8217;ve been really impressed with is dojo.connect. This connect method not only listens to DOM events but also allows you to listen to when a regular function is executed. Lets examine what dojo.connect is and the different methods by which you can use dojo.connect within any Dojo [...]<p><strong>Follow Me!</strong> <a
href="http://twitter.com/davidwalshblog">Twitter</a> | <a
href="http://www.facebook.com/#!/pages/David-Walsh-Blog/186644584869">Facebook</a> | <a
href="http://www.linkedin.com/in/davidjameswalsh">LinkedIn</a> | <a
href="http://mootools.net/forge/profile/davidwalsh">MooTools Forge.</a><br/><br/>Full David Walsh Blog Post: <a
href="http://davidwalsh.name/dojo-connect">dojo.connect: A Powerful Object and Event&nbsp;Listener</a></p>Related posts:<ol><li><a
href='http://davidwalsh.name/mootools-jquery-dojo' rel='bookmark' title='Permanent Link: Accomplishing Common Tasks Using MooTools, jQuery, and&nbsp;Dojo'>Accomplishing Common Tasks Using MooTools, jQuery, and&nbsp;Dojo</a></li><li><a
href='http://davidwalsh.name/dojo-mootools-jquery' rel='bookmark' title='Permanent Link: Accomplishing Common Tasks Using MooTools, jQuery, and Dojo&nbsp;III'>Accomplishing Common Tasks Using MooTools, jQuery, and Dojo&nbsp;III</a></li><li><a
href='http://davidwalsh.name/dojo-context-menu' rel='bookmark' title='Permanent Link: Create a Context Menu with Dojo and&nbsp;Dijit'>Create a Context Menu with Dojo and&nbsp;Dijit</a></li><li><a
href='http://davidwalsh.name/quickboxes-dojo' rel='bookmark' title='Permanent Link: QuickBoxes for&nbsp;Dojo'>QuickBoxes for&nbsp;Dojo</a></li><li><a
href='http://davidwalsh.name/mootools-event' rel='bookmark' title='Permanent Link: MooTools Plugin:&nbsp;Event.Mock'>MooTools Plugin:&nbsp;Event.Mock</a></li></ol>]]></description> <content:encoded><![CDATA[<p>One of the pieces of the Dojo Toolkit I&#8217;ve been really impressed with is <span
class="function">dojo.connect</span>.  This <span
class="function">connect</span> method not only listens to DOM events but also allows you to listen to when a regular function is executed.  Lets examine what <span
class="function">dojo.connect</span> is and the different methods by which you can use <span
class="function">dojo.connect</span> within any Dojo application.</p><h2>dojo.connect&#8217;s&nbsp;Signature</h2><pre class="js">
dojo.connect = function(
	obj,		//Object|null
	event,		//String
	context,	//Object|null
	method,		//String|Function
	dontFix		//Boolean
) //.....
</pre><p>A more detailed explanation of each argument <em>(as taken from the Dojo documentation)</em>:</p><ul><li><strong>obj:</strong> The source object for the event function. Defaults to dojo.global if null. If obj is a DOM node, the connection is delegated to the DOM event manager (unless dontFix is true).</li><li><strong>event:</strong> Name of the event function in obj. I.e. identifies a property obj[event].</li><li><strong>context:</strong> The object that method will receive as &#8220;this&#8221;. If context is null and method is a function, then method inherits the context of event. If method is a string then context must be the source object object for method (context[method]). If context is null, dojo.global is used.</li><li><strong>method:</strong> A function reference, or name of a function in context. The function identified by method fires after event does. method receives the same arguments as the event. See context argument comments for information on method&#8217;s scope.</li><li><strong>dontFix</strong>: If obj is a DOM node, set dontFix to true to prevent delegation of this connection to the DOM event manager.</li></ul><p>dojo.connect returns a handle that you will need to remove the connection later.  Also note that <strong>any arguments passed to the object (function) will be received by the listener!</strong> Holy hell that&#8217;s useful!</p><h2>Example Usages: DOM Node Event&nbsp;Handling</h2><pre class="js">
var eventHandle = dojo.connect(dojo.byId('myElement'),'onclick',null,function() { //null = dojo.global
	alert('you clicked myElement');
});

//...or:

var eventHandle = dojo.connect(dojo.byId('myElement'),'onclick',function() { //context isn't required
	alert('you clicked myElement');
});

</pre><p>When <span
class="function">myElement</span> is clicked, my messaged is alerted.</p><h2>Example Usages: Object&nbsp;Handling</h2><pre class="js">
var someFunction = function() {
	alert('run!');
};
var val = dojo.connect(null,'someFunction',null,function() { //null = dojo.global
	alert('you ran someFunction!()');
});
</pre><p>When <span
class="function">someFunction</span> is called, my listener function alerts the message.  How cool is that?!</p><h2>Example Usages: NodeList Event&nbsp;Handling</h2><pre class="js">
dojo.query('.myElements').connect('onClick',function() { //this becomes the "current" element
	alert('you clicked this link');
});
</pre><p>Event handling even works on <span
class="function">dojo.connect</span> &#8212; you don&#8217;t need to cycle through each element in the collection to add the event listeners individually.</p><h2>Example Usage: Removing an&nbsp;Event</h2><pre class="js">
var eventHandle = dojo.connect(dojo.byId('myElement'),'onclick',function() { //context isn't required
	alert('you clicked myElement');
});

//....
//something happens; we want to remove the event listener
//....

dojo.disconnect(eventHandle);
</pre><p>We pass the handle provided by <span
class="function">dojo.connect</span> to disconnect the listener.</p><p>That&#8217;s just a quick taste of what you can do with <span
class="function">dojo.connect</span>.  Be sure to check out Dojo and experiment with the different ways you can use <span
class="function">dojo.connect</span>.  Since <span
class="function">dojo.connect</span> is one of the core methods of the library, <span
class="function">dojo.connect</span> is used everywhere. <span
class="function">dojo.connect</span> also plays an important role within Dijit, Dojo&#8217;s UI branch.</p><p><strong>Follow Me!</strong> <a
href="http://twitter.com/davidwalshblog">Twitter</a> | <a
href="http://www.facebook.com/#!/pages/David-Walsh-Blog/186644584869">Facebook</a> | <a
href="http://www.linkedin.com/in/davidjameswalsh">LinkedIn</a> | <a
href="http://mootools.net/forge/profile/davidwalsh">MooTools Forge.</a><br/><br/>Full David Walsh Blog Post: <a
href="http://davidwalsh.name/dojo-connect">dojo.connect: A Powerful Object and Event&nbsp;Listener</a></p><p>Related posts:<ol><li><a
href='http://davidwalsh.name/mootools-jquery-dojo' rel='bookmark' title='Permanent Link: Accomplishing Common Tasks Using MooTools, jQuery, and&nbsp;Dojo'>Accomplishing Common Tasks Using MooTools, jQuery, and&nbsp;Dojo</a></li><li><a
href='http://davidwalsh.name/dojo-mootools-jquery' rel='bookmark' title='Permanent Link: Accomplishing Common Tasks Using MooTools, jQuery, and Dojo&nbsp;III'>Accomplishing Common Tasks Using MooTools, jQuery, and Dojo&nbsp;III</a></li><li><a
href='http://davidwalsh.name/dojo-context-menu' rel='bookmark' title='Permanent Link: Create a Context Menu with Dojo and&nbsp;Dijit'>Create a Context Menu with Dojo and&nbsp;Dijit</a></li><li><a
href='http://davidwalsh.name/quickboxes-dojo' rel='bookmark' title='Permanent Link: QuickBoxes for&nbsp;Dojo'>QuickBoxes for&nbsp;Dojo</a></li><li><a
href='http://davidwalsh.name/mootools-event' rel='bookmark' title='Permanent Link: MooTools Plugin:&nbsp;Event.Mock'>MooTools Plugin:&nbsp;Event.Mock</a></li></ol></p>]]></content:encoded> <wfw:commentRss>http://davidwalsh.name/dojo-connect/feed</wfw:commentRss> <slash:comments>0</slash:comments> </item> </channel> </rss>
<!-- Performance optimized by W3 Total Cache. Learn more: http://www.w3-edge.com/wordpress-plugins/

Minified using disk
Page Caching using disk (enhanced) (user agent is rejected)
Database Caching 129/392 queries in 4.586 seconds using disk

Served from: davidwalsh.name @ 2010-09-02 23:25:30 -->