<?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/"
xmlns:series="http://unfoldingneurons.com/"
><channel><title>David Walsh :: Legendary scribbles about JavaScript, HTML5, AJAX, PHP, CSS, and ∞. &#187; HTML5</title> <atom:link href="http://davidwalsh.name/tutorials/html5/feed" rel="self" type="application/rss+xml" /><link>http://davidwalsh.name</link> <description>Legendary scribbles about JavaScript, HTML5, AJAX, PHP, CSS, and ∞.</description> <lastBuildDate>Sat, 04 Feb 2012 19:28:58 +0000</lastBuildDate> <language>en</language> <sy:updatePeriod>hourly</sy:updatePeriod> <sy:updateFrequency>1</sy:updateFrequency> <generator>http://wordpress.org/?v=3.3</generator> <item><title>dat.gui:  Exceptional JavaScript Interface&#160;Controller</title><link>http://davidwalsh.name/dat-gui</link> <comments>http://davidwalsh.name/dat-gui#comments</comments> <pubDate>Thu, 11 Aug 2011 14:15:55 +0000</pubDate> <dc:creator>David Walsh</dc:creator> <category><![CDATA[HTML5]]></category> <category><![CDATA[JavaScript]]></category><guid
isPermaLink="false">http://davidwalsh.name/?p=5281</guid> <description><![CDATA[We all love trusted JavaScript frameworks like MooTools, jQuery, and Dojo, but there&#8217;s a big push toward using focused micro-frameworks for smaller purposes. Of course, there are positives and negatives to using them.  Positives include smaller JS footprint (especially good for mobile) and less cruft, negatives being that they don&#8217;t have the community behind them [...]<p><a
href="http://davidwalsh.name/dat-gui">dat.gui:  Exceptional JavaScript Interface&nbsp;Controller</a> is a post from: <a
href="http://davidwalsh.name">David Walsh :: Legendary scribbles about JavaScript, HTML5, AJAX, PHP, CSS, and ∞.</a></p> ]]></description> <content:encoded><![CDATA[<p><img
src="http://davidwalsh.name/dw-content/dat-gui.png" alt="dat.gui JavaScript" /></p><p>We all love trusted JavaScript frameworks like MooTools, jQuery, and Dojo, but there&#8217;s a big push toward using focused micro-frameworks for smaller purposes. Of course, there are positives and negatives to using them.  Positives include smaller JS footprint (especially good for mobile) and less cruft, negatives being that they don&#8217;t have the community behind them to drive growth and the developer that uses multiple micro-frameworks has to work with inconsistent APIs.  To each their own;  I don&#8217;t have a strong feeling either way, as it depends on the project.</p><p>One nice resource I recently stumbled upon is <code>dat.gui</code>. <code>dat.gui</code> advertises itself as <em>a lightweight controller library that allows you to easily manipulate variables and fire functions on the fly.   </em>That&#8217;s a pretty general statement but <code>dat.gui</code> appears to be a very general framework.  The premise is object and property management within a GUI panel.  Let&#8217;s take a look at how <code>dat.gui</code> can be used.</p><div
class="actions"><a
href="http://davidwalsh.name/dw-content/dat-gui.php" class="demo">View Demo</a><div
class="clear"></div></div><p><code>dat.gui</code>&#8216;s niche is in listening to and controlling data such that it can be visualized into charts or other graphics.  Creating a new DAT.GUI instance provides a new sliding pane for which to add controls to:</p><pre class="js">
// Create an instance, which also creates a UI pane
var gui = new DAT.GUI();
</pre><p>With the pane ready, new controls can be added.  Fields can be of type string, number, boolean, or function, with a number slider available depending on options passed to it.  Here&#8217;s how you can create a field of each type:</p><pre class="js">

// My sample abject
var obj = {
	name: "David Walsh",
	num: 23,
	winner: true
};

// String field
gui.add(obj, "name");

// Number field with slider
gui.add(obj, "num").min(1).max(50).step(1);

// Checkbox field
gui.add(obj, "winner");

</pre><p>Since properties are changed directly on the object itself, there&#8217;s not &#8220;setter&#8221; and so <code>dat.gui</code> provides a <code>listen</code> function to do just that &#8212; list for changes:</p><pre class="js">
// Listen to changes within the GUI
gui.add(obj, "name").onChange(function(newValue) {
	console.log("Value changed to:  ", newValue);
});

// Listen to changes outside the GUI - GUI will update when changed from outside
gui.add(obj, "name").listen();
</pre><p>Those are the dead basics of the <code>dat.gui</code> library.  Note that I&#8217;ve not yet mentioned what the result looks like.  That&#8217;s because it&#8217;s up to you to create the visual aspects based on property values.  The demo that ships with <code>dat.gui</code> is a very creative dot-based constant animation.  The animation magic lies within the FizzyText function.  FizzyText is a more sizable function that does the animation, but let&#8217;s take a look at the <code>dat.gui</code> code:</p><pre class="js">
var fizzyText = new FizzyText("david walsh");
var gui = new DAT.GUI();

// Text field
gui.add(fizzyText, "message");

// Sliders with min + max
gui.add(fizzyText, "maxSize").min(0.5).max(7);
gui.add(fizzyText, "growthSpeed").min(0.01).max(1).step(0.05);
gui.add(fizzyText, "speed", 0.1, 2, 0.05); // shorthand for min/max/step

// Sliders with min, max and increment.
gui.add(fizzyText, "noiseStrength", 10, 100, 5);

// Boolean checkbox
gui.add(fizzyText, "displayOutline");
</pre><p>Tinker with the pane fields and the animation instantly changes!</p><div
class="actions"><a
href="http://davidwalsh.name/dw-content/dat-gui.php" class="demo">View Demo</a><div
class="clear"></div></div><p>JavaScript, more than any other language, seems to provide the most ability to make powerful changes with very little code.  <code>dat.gui</code> is proof of that.  The demo provided here is the same demo provided within the <code>dat.gui</code> repository, mostly because topping the effect would be a hell of a feat.  When you get a few moments, go play around with <code>dat.gui</code> &#8212; it&#8217;s really &#8230; dat &#8230; good.</p><p><a
href="http://davidwalsh.name/dat-gui">dat.gui:  Exceptional JavaScript Interface&nbsp;Controller</a> is a post from: <a
href="http://davidwalsh.name">David Walsh :: Legendary scribbles about JavaScript, HTML5, AJAX, PHP, CSS, and ∞.</a></p> ]]></content:encoded> <wfw:commentRss>http://davidwalsh.name/dat-gui/feed</wfw:commentRss> <slash:comments>1</slash:comments> </item> <item><title>Drag and Drop MooTools File&#160;Uploads</title><link>http://davidwalsh.name/mootools-upload</link> <comments>http://davidwalsh.name/mootools-upload#comments</comments> <pubDate>Wed, 10 Aug 2011 14:05:24 +0000</pubDate> <dc:creator>David Walsh</dc:creator> <category><![CDATA[AJAX]]></category> <category><![CDATA[CSS]]></category> <category><![CDATA[HTML5]]></category> <category><![CDATA[MooTools]]></category><guid
isPermaLink="false">http://davidwalsh.name/?p=5279</guid> <description><![CDATA[Honesty hour confession:  file uploading within the web browser sucks.  It just does.  Like the ugly SELECT element, the file input is almost unstylable and looks different on different platforms.  Add to those criticism the fact that we&#8217;re all used to drag and drop operations, yet up until recently, you couldn&#8217;t drag files into a [...]<p><a
href="http://davidwalsh.name/mootools-upload">Drag and Drop MooTools File&nbsp;Uploads</a> is a post from: <a
href="http://davidwalsh.name">David Walsh :: Legendary scribbles about JavaScript, HTML5, AJAX, PHP, CSS, and ∞.</a></p> ]]></description> <content:encoded><![CDATA[<p>Honesty hour confession:  file uploading within the web browser sucks.  It just does.  Like the <a
href="http://davidwalsh.name/jquery-chosen">ugly SELECT element</a>, the file input is almost unstylable and looks different on different platforms.  Add to those criticism the fact that we&#8217;re all used to drag and drop operations, yet up until recently, you couldn&#8217;t drag files into a browser to upload them, making file uploading within the browser unintuitive.  With recent advancements in browser technology, the drag and drop method is now supported, but it doesn&#8217;t look good without a bit of work.  Luckily MooTools Core Developer Arian Stolwijk has created a <a
href="https://github.com/arian/mootools-form-upload" rel="nofollow">set of classes</a> to accommodate styling drag and drop file uploading within the browser.  Let&#8217;s have a look at how it works!</p><div
class="actions"><a
href="http://davidwalsh.name/dw-content/mootools-upload.php" class="demo">View Demo</a><div
class="clear"></div></div><h2>The&nbsp;HTML</h2><p>The basic setup is the same as a traditional form upload within the browser;  a <code>FORM</code> element with an <code>INPUT</code> of file type:</p><pre class="html">
&lt;form method="post" action="mootools-upload.php" enctype="multipart/form-data" id="uploadForm"&gt;
&lt;div&gt;
	&lt;div class="formRow"&gt;
		&lt;label for="file" class="floated"&gt;File: &lt;/label&gt;
		&lt;input type="file" id="file" name="file[]" multiple&gt;&lt;br&gt;
	&lt;/div&gt;

	&lt;div class="formRow"&gt;
		&lt;input type="submit" name="upload" value="Upload"&gt;
	&lt;/div&gt;
&lt;/div&gt;
&lt;/form&gt;
</pre><p>This setup allows file uploading even if JavaScript is not enabled.  <em>(Note to IT snobs:  get over yourselves and turn JavaScript back on)</em></p><h2>The&nbsp;CSS</h2><p>The &#8220;drop zone&#8221; and &#8220;progress bar&#8221; areas can be easily styled in any fashion you&#8217;d like.  My sample CSS looks like this:</p><pre class="css">
.droppable {
	border: #ccc 1px solid;
	border-radius: 8px;
	background: #eee;
	color: #666;
	padding: 20px;
	margin: 10px;
	clear: both;
	text-align: center;
}

.droppable.hover {
	background: #ddd;
}

.uploadList {
	margin: 0;
	padding: 0;
	list-style: none;
}

.uploadItem {
	overflow: hidden;
	border-bottom: #BCBCBC 1px solid;
	margin: 0 20px;
	padding: 3px;
}

.uploadItem span {
	overflow: hidden;
	width: 150px;
	float: left;
	display: block;
}

a.addInputRow,
a.delInputRow,
.uploadItem a {
	display: inline-block;
	background: url(add.png) no-repeat;
	height: 16px;
	width: 16px;
	text-indent: -999px;
}

.uploadItem a {
	float: left;
	display: block;
	padding-left: 20px;
	background-image: url(delete.png);
}

a.delInputRow {
	background-image: url(delete.png);
}

.progress {
	margin: 5px 0;
	height: 15px;
	border-radius: 3px;
	background: #545A74;
}
</pre><p>Since we have (unfortunately) become accustomed to the ugly <code>INPUT type=file</code>, my only CSS advice is to make sure you make not only your &#8220;drop zone&#8221; apparent but explain that the user should drag and drop.</p><h2>The MooTools&nbsp;JavaScript</h2><p>Arian has provided 3 JavaScript classes within his mootools-form-upload repository:</p><ul><li><code>Form.Upload</code>:  The main worker class, detecting the browser capabilities and building a file uploader based on those features</li><li><code>Form.MultiFileInput</code>:  A class which builds and manages the list of files to be uploaded.</li><li><code>Request.File</code>:  Manages the FormData object, sends files, and reports progress.</li></ul><p>Another resource, iFrameFormRequest, can be included in case the user is rocking a legacy browser.  With the resources above added to the page, let&#8217;s set up our drag and drop file uploader:</p><pre class="js">
window.addEvent('domready', function(){
	
	// Create the file uploader
	var upload = new Form.Upload('file', {
		dropMsg: "Drop files here",
		onComplete: function(){
			alert('Files uploaded!');
		}
	});

	// Use iFrameFormRequest, which posts to iFrame 
	if (!upload.isModern()) {
		new iFrameFormRequest('uploadForm', {
			onComplete: function(response){
				alert('Files uploaded!');
			}
		});
	}

});
</pre><p>We start by creating an instance of <code>Form.Upload</code>, passing it the <code>INPUT</code> node and the class options.  The <code>onComplete</code> option is most important, as it represents the event that fires when all uploads have completed, allowing you to notify the user.</p><p>For more customizable uploads, like notifications for progress and success, you can pair <code>Form.MultipleFileInput</code> and <code>Request.File</code> directly:</p><pre class="js">
// From ReadMe.md

// the input element, the list (ul) and the drop zone element.
var input, list, drop;
// Form.MultipleFileInput instance
var inputFiles = new Form.MultipleFileInput(input, list, drop, {
    onDragenter: drop.addClass.pass('hover', drop),
    onDragleave: drop.removeClass.pass('hover', drop),
    onDrop: drop.removeClass.pass('hover', drop)
});

// Request instance;
var request = new Request.File({
    url: 'files.php'
    // onSuccess
    // onProgress
});

myForm.addEvent('submit', function(event){
    event.preventDefault();
    inputFiles.getFiles().each(function(file){
        request.append('url[]' , file);
    });
    request.send();
});

</pre><p>This solution would be good for using detailed progress bars.</p><div
class="actions"><a
href="http://davidwalsh.name/dw-content/mootools-upload.php" class="demo">View Demo</a><div
class="clear"></div></div><p>Outstanding work once again by Arian.  His contribution to the MooTools JavaScript framework has been priceless, and he continues that effort with his drag and drop file upload system.  These classes prove the power of MooTools and the advancement of browsers today.  Give your users the elegant option of drag and drop uploads!</p><p><a
href="http://davidwalsh.name/mootools-upload">Drag and Drop MooTools File&nbsp;Uploads</a> is a post from: <a
href="http://davidwalsh.name">David Walsh :: Legendary scribbles about JavaScript, HTML5, AJAX, PHP, CSS, and ∞.</a></p> ]]></content:encoded> <wfw:commentRss>http://davidwalsh.name/mootools-upload/feed</wfw:commentRss> <slash:comments>16</slash:comments> </item> <item><title>window.postMessage Tip:  Child-To-Parent&#160;Communication</title><link>http://davidwalsh.name/window-iframe</link> <comments>http://davidwalsh.name/window-iframe#comments</comments> <pubDate>Wed, 26 Jan 2011 15:31:20 +0000</pubDate> <dc:creator>David Walsh</dc:creator> <category><![CDATA[HTML5]]></category> <category><![CDATA[JavaScript]]></category><guid
isPermaLink="false">http://davidwalsh.name/?p=5161</guid> <description><![CDATA[I wrote a super epic post a few months back about the window.postMessage API that&#8217;s sweeping the nation.  window.postMessage allows you to send messages not only across frames (regular frame or iframe) but also across domains.  My post showed interaction from parent to child and back to the parent, but didn&#8217;t detail passing messages from [...]<p><a
href="http://davidwalsh.name/window-iframe">window.postMessage Tip:  Child-To-Parent&nbsp;Communication</a> is a post from: <a
href="http://davidwalsh.name">David Walsh :: Legendary scribbles about JavaScript, HTML5, AJAX, PHP, CSS, and ∞.</a></p> ]]></description> <content:encoded><![CDATA[<p>I wrote a super epic post a few months back about the <code>window.postMessage</code> API that&#8217;s sweeping the nation.  <code>window.postMessage</code> allows you to send messages not only across frames (regular frame or iframe) but also across domains.  My post showed interaction from parent to child and back to the parent, but didn&#8217;t detail passing messages from a child to a parent without the parent initializing the conversation.  Let me show you how you can initialize that conversation from child to parent</p><p><img
src="http://davidwalsh.name/dw-content/window-postmessage.jpg" alt="window.postmessage" /></p><h2>The&nbsp;JavaScript</h2><p>The parent object provides a reference to the main window from the child.  So if I have an iFrame and console the parent within it, the console will read:</p><pre class="js">
// Every two seconds....
setInterval(function() {
	// Send the message "Hello" to the parent window
	// ...if the domain is still "davidwalsh.name"
	parent.postMessage("Hello","http://davidwalsh.name");
},1000);
</pre><p>Since we now have hold of the window, we can postMessage to it:</p><pre class="js">
// Create IE + others compatible event handler
var eventMethod = window.addEventListener ? "addEventListener" : "attachEvent";
var eventer = window[eventMethod];
var messageEvent = eventMethod == "attachEvent" ? "onmessage" : "message";

// Listen to message from child window
eventer(messageEvent,function(e) {
  console.log('parent received message!:  ',e.data);
},false);
</pre><p>The directive above triggers the iFrame to send a message to the parent window every 3 seconds.  No initial message from the main window needed!</p><p><a
href="http://davidwalsh.name/window-iframe">window.postMessage Tip:  Child-To-Parent&nbsp;Communication</a> is a post from: <a
href="http://davidwalsh.name">David Walsh :: Legendary scribbles about JavaScript, HTML5, AJAX, PHP, CSS, and ∞.</a></p> ]]></content:encoded> <wfw:commentRss>http://davidwalsh.name/window-iframe/feed</wfw:commentRss> <slash:comments>1</slash:comments> </item> <item><title>HTML5 Placeholder Styling with&#160;CSS</title><link>http://davidwalsh.name/html5-placeholder-css</link> <comments>http://davidwalsh.name/html5-placeholder-css#comments</comments> <pubDate>Mon, 27 Dec 2010 15:46:41 +0000</pubDate> <dc:creator>David Walsh</dc:creator> <category><![CDATA[CSS]]></category> <category><![CDATA[HTML5]]></category><guid
isPermaLink="false">http://davidwalsh.name/?p=5146</guid> <description><![CDATA[4/25/2011: This attribute is not styleable as of Opera 11. Internet Explorer 10 will introduce placeholder support. Last week I showed you how you could style selected text with CSS. I&#8217;ve searched for more interesting CSS style properties and found another: INPUT placeholder styling. Let me show you how to style placeholder text within INPUTelements [...]<p><a
href="http://davidwalsh.name/html5-placeholder-css">HTML5 Placeholder Styling with&nbsp;CSS</a> is a post from: <a
href="http://davidwalsh.name">David Walsh :: Legendary scribbles about JavaScript, HTML5, AJAX, PHP, CSS, and ∞.</a></p> ]]></description> <content:encoded><![CDATA[<div
class="update"><p>4/25/2011:  This attribute is not styleable as of Opera 11.  Internet Explorer 10 will introduce <code>placeholder</code> support.</p></div><p>Last week I showed you how you could <a
href="http://davidwalsh.name/css-selection">style selected text with CSS</a>. I&#8217;ve searched for more interesting CSS style properties and found another: <code>INPUT</code> placeholder styling. Let me show you how to style placeholder text within <code>INPUT</code>elements with some unique CSS code.</p><div
class="actions"><a
href="http://davidwalsh.name/dw-content/placeholder-style.php" class="demo">View Demo</a><div
class="clear"></div></div><h2>The&nbsp;CSS</h2><p>Firefox employs a different pattern than Safari and Chrome. Each property name is self-explanatory though:</p><pre class="css">
/* all */
::-webkit-input-placeholder	{ color:#f00; }
input:-moz-placeholder { color:#f00; }

/* individual: webkit */
#field2::-webkit-input-placeholder { color:#00f; }
#field3::-webkit-input-placeholder { color:#090; background:lightgreen; text-transform:uppercase; }
#field4::-webkit-input-placeholder { font-style:italic; text-decoration:overline; letter-spacing:3px; color:#999; }

/* individual: mozilla */
#field2::-moz-placeholder { color:#00f; }
#field3::-moz-placeholder { color:#090; background:lightgreen; text-transform:uppercase; }
#field4::-moz-placeholder { font-style:italic; text-decoration:overline; letter-spacing:3px; color:#999; }
</pre><p>You will only want to employ the most basic of styles to the placeholder. Color, font-style, and font-variant are probably the styles you will want to employ. Go too far with your placeholder styling and you may create the animated GIF of input styles.  Note that Mozilla Firefox doesn&#8217;t support placeholder styling until version 4.</p><div
class="actions"><a
href="http://davidwalsh.name/dw-content/placeholder-style.php" class="demo">View Demo</a><div
class="clear"></div></div><p>Styling elements with the placeholder attribute is something you don&#8217;t need to do but could be just another one of those small details that sets your website apart from other websites. Hopefully IE9 and Opera soon follow suit in allowing styling of placeholder text within INPUT elements&#8230;or expose their API for doing so!</p><p><a
href="http://davidwalsh.name/html5-placeholder-css">HTML5 Placeholder Styling with&nbsp;CSS</a> is a post from: <a
href="http://davidwalsh.name">David Walsh :: Legendary scribbles about JavaScript, HTML5, AJAX, PHP, CSS, and ∞.</a></p> ]]></content:encoded> <wfw:commentRss>http://davidwalsh.name/html5-placeholder-css/feed</wfw:commentRss> <slash:comments>18</slash:comments> </item> <item><title>WebSocket and&#160;Socket.IO</title><link>http://davidwalsh.name/websocket</link> <comments>http://davidwalsh.name/websocket#comments</comments> <pubDate>Mon, 29 Nov 2010 15:04:38 +0000</pubDate> <dc:creator>David Walsh</dc:creator> <category><![CDATA[HTML5]]></category> <category><![CDATA[JavaScript]]></category><guid
isPermaLink="false">http://davidwalsh.name/?p=5122</guid> <description><![CDATA[My favorite web technology is quickly becoming the WebSocket API. WebSocket provides a welcomed alternative to the AJAX technologies we&#8217;ve been making use of over the past few years. This new API provides a method to push messages from client to server efficiently and with a simple syntax. Let&#8217;s take a look at the HTML5 [...]<p><a
href="http://davidwalsh.name/websocket">WebSocket and&nbsp;Socket.IO</a> is a post from: <a
href="http://davidwalsh.name">David Walsh :: Legendary scribbles about JavaScript, HTML5, AJAX, PHP, CSS, and ∞.</a></p> ]]></description> <content:encoded><![CDATA[<p><a
href="http://davidwalsh.name/dw-content/websockets.zip"><img
src="http://davidwalsh.name/dw-content/socketio.jpg" alt="WebSocket Socket.IO" /></a></p><p>My favorite web technology is quickly becoming the WebSocket API.  WebSocket provides a welcomed alternative to the AJAX technologies we&#8217;ve been making use of over the past few years.  This new API provides a method to push messages from client to server efficiently and with a simple syntax.  Let&#8217;s take a look at the HTML5 WebSocket API: its use on the client side, server side, and an outstanding wrapper API called Socket.IO.</p><div
class="actions"><a
href="http://davidwalsh.name/dw-content/websockets.zip" class="demo">View Demo</a><div
class="clear"></div></div><h2>What is the WebSocket&nbsp;API?</h2><p>The WebSocket API is the next generation method of asynchronous communication from client to server.  Communication takes place over single TCP socket using the <code>ws</code> (unsecure) or <code>wss</code> (secure) protocol and can be used by any client or server application.  WebSocket is currently being standardized by the W3C.  WebSocket is currently implemented in Firefox 4, Chrome 4, Opera 10.70, and Safari 5.</p><p>What&#8217;s great about the WebSocket API that server and client can push messages to each other at any given time.  WebSocket is not limited in its nature the way that AJAX (or XHR) is;  AJAX technologies require a request to be made by the client, whereas WebSocket servers and clients can push each other messages.  XHR is also limited by domain;  the WebSocket API allows cross-domain messaging with no fuss.</p><p>AJAX technology was a clever usage of a feature not designed to be used the way it is today.  WebSocket was created for the specific purpose of bi-direction message pushing.</p><h2>WebSocket API&nbsp;Usage</h2><p>Focusing on the client side API only (because each server side language will have its own API), the following snippet opens a connection, creates event listeners for connect, disconnect, and message events, sends a message back to the server, and closes the connection.</p><pre class="js">
// Create a socket instance
var socket = new WebSocket('ws://localhost:8080');

// Open the socket
socket.onopen = function(event) {
	
	// Send an initial message
	socket.send('I am the client and I\'m listening!');
	
	// Listen for messages
	socket.onmessage = function(event) {
		console.log('Client received a message',event);
	};
	
	// Listen for socket closes
	socket.onclose = function(event) {
		console.log('Client notified socket has closed',event);
	};
	
	// To close the socket....
	//socket.close()
	
};
</pre><p>Let&#8217;s take a look at the individual pieces of the snippet above.  The argument provided to WebSocket represents the URL to the address listening for socket connections. <code>onopen</code>, <code>onclose</code>, and <code>onmessage</code> methods connect you to events on the socket instance.  Each of these methods provides an event which gives insight as to the state of the socket.<p>The <code>onmessage</code> event provides a data property which contains the body of the message.  The message body must be a string, so serialization/deserialization strategies will be needed to pass more data.</p><p>The syntax is extremely simple which makes using WebSockets incredibly easy&#8230;unless the client doesn&#8217;t support WebSocket.  Internet Explorer does not currently support WebSocket.  There are a few fallback transports that you can use if the client doesn&#8217;t support WebSocket:</p><ul><li><strong>Flash</strong> &#8211; Flash can provide a simple alternative.  The obvious drawback is that Flash is not installed on all clients, and in the case of the iPhone/iPad, cannot be.</li><li><strong>AJAX Long-Polling</strong> &#8211; AJAX long-polling has been used for quite a while to simulate WebSocket.  It&#8217;s a technology that works but isn&#8217;t optimized for message sending.  I wouldn&#8217;t call AJAX long-polling a hack but it&#8217;s simply not an optimal method.</li></ul><p>Wouldn&#8217;t it be great if an API was available that would provide WebSocket event handling, fallback transports, and a server side solution, all within one API?  Luckily <a
href="http://devthought.com" rel="nofollow">Guillermo Rauch</a> has created <a
href="http://socket.io/" rel="nofollow">Socket.IO</a>.</p><h2>WebSocket with&nbsp;Socket.IO</h2><p>Socket.IO is a WebSocket API created by Guillermo Rauch, CTO of <a
href="http://learnboost.com" rel="nofollow">LearnBoost</a> and lead scientist of LearnBoost Labs.  Socket.IO will use feature detection to decide if the connection will be established with WebSocket, AJAX long polling, Flash, etc., making creating realtime apps that work everywhere a snap.  Socket.IO also provides an API for NodeJS which looks very much like the client side API.</p><h3>Client &#8211; Socket.IO&nbsp;Setup</h3><p>Socket.IO is available for download at GitHub.  You can include the <code>socket.io.js</code> file or you can pull Socket.IO from CDN:</p><pre class="html">
&lt;script src="http://cdn.socket.io/stable/socket.io.js"&gt;&lt;/script&gt;
</pre><p>With Socket.IO available in the page, it&#8217;s time to create a Socket:</p><pre class="js">
// Create SocketIO instance, connect
var socket = new io.Socket('localhost',{
	port: 8080
});
socket.connect(); 

// Add a connect listener
socket.on('connect',function() {
	console.log('Client has connected to the server!');
});
// Add a connect listener
socket.on('message',function(data) {
	console.log('Received a message from the server!',data);
});
// Add a disconnect listener
socket.on('disconnect',function() {
	console.log('The client has disconnected!');
});

// Sends a message to the server via sockets
function sendMessageToServer(message) {
	socket.send(message);
}
</pre><p>Socket.IO simplifies the WebSocket API and unifies the APIs of its fallback transports.  Transports include:</p><ul><li>WebSocket</li><li>Flash Socket</li><li>AJAX long-polling</li><li>AJAX multipart streaming</li><li>IFrame</li><li>JSONP polling</li></ul><p>You may set any of the Socket.IO instance&#8217;s options with a second argument to the constructor.  Options include:</p><ul><li><code>port</code> &#8211; the port to connect to</li><li><code>transports</code> &#8211; an array containing the different transport types in order by preference []</li><li><code>transportOptions</code> &#8211; an object with additional properties to pass to the transport</li></ul><p>Socket.IO also provides the usual connect, disconnect, and message events that the native WebSocket API provides.  Socket also provides an on method which wraps each event type, much the way Node does.</p><h3>NodeJS &#8211; Socket.IO&nbsp;Setup</h3><p>The server side solution provided by Socket.IO allows unification of the client and server side APIs.  With Node, you create a typical HTTP server but then pass the server instance to SocketIO.  From there, you create connection, disconnect, and message listeners much the way you did on the client side.</p><p>A sample server side script would look very much like this:</p><pre class="js">
// Require HTTP module (to start server) and Socket.IO
var http = require('http'), io = require('socket.io');

// Start the server at port 8080
var server = http.createServer(function(req, res){ 

	// Send HTML headers and message
	res.writeHead(200,{ 'Content-Type': 'text/html' }); 
	res.end('&lt;h1&gt;Hello Socket Lover!&lt;/h1&gt;');
});
server.listen(8080);

// Create a Socket.IO instance, passing it our server
var socket = io.listen(server);

// Add a connect listener
socket.on('connection', function(client){ 
	
	// Success!  Now listen to messages to be received
	client.on('message',function(event){ 
		console.log('Received message from client!',event);
	});
	client.on('disconnect',function(){
		clearInterval(interval);
		console.log('Server has disconnected');
	});

});
</pre><p>You can run the server portion (assuming you have NodeJS installed) from command line with:</p><pre class="shell">node socket-server.js</pre><p>Now your client and server can push messages back and forth!  Within the NodeJS script, you can create a periodical message sender using some simple JavaScript:</p><pre class="js">
// Create periodical which ends a message to the client every 5 seconds
var interval = setInterval(function() {
	client.send('This is a message from the server!  ' + new Date().getTime());
},5000);
</pre><p>The server side script will push a message to the client every five seconds!</p><h2>dojox.Socket and&nbsp;Socket.IO</h2><p><a
href="http://www.persvr.org">Persevere</a> creator <a
href="http://github.com/kriszyp">Kris Zyp</a> has created <code>dojox.Socket</code>. <code>dojox.Socket</code> wraps the WebSocket API in an API consistent with Dojo and provides a long-polling alternative if the client doesn&#8217;t support WebSocket. Here&#8217;s how you can use <code>dojox.Socket</code> on the client side and Socket.IO on the server side:</p><pre class="js">
var args, ws = typeof WebSocket != 'undefined';
var socket = dojox.socket(args = {
	url: ws ? '/socket.io/websocket' : '/socket.io/xhr-polling',
	headers:{
		'Content-Type':'application/x-www-urlencoded'
	},
	transport: function(args, message){
		args.content = message; // use URL-encoding to send the message instead of a raw body
		dojo.xhrPost(args);
	};
});
var sessionId;
socket.on('message', function(){
	if (!sessionId){
		sessionId = message;
		args.url += '/' + sessionId;
	}else if(message.substr(0, 3) == '~h~'){
		// a heartbeat
	}
});
</pre><p><code>dojox.socket.Reconnect</code> has also been created to automatically reconnect if the socket loses connection. Look forward to <code>dojox.Socket</code> debuting in Dojo 1.6.</p><h2>Practical&nbsp;Applications</h2><p>There are many practical applications for WebSocket.  WebSocket is ideal for most client-to-server asynchronous purposes, chat within the browser being the most prominent.  WebSocket is used to day by most many companies because of its efficiency.  Socket.IO is in use by many organizations and was very popular at the Node KnockOut contest.</p><h2>WebSocket&nbsp;Resources</h2><p>There&#8217;s not a great deal of information available about WebSocket so I&#8217;ve rounded up a few helpful resources:</p><ul><li><a
href="http://socket.io/" rel="nofollow">Socket.IO Website</a></li><li><a
href="http://en.wikipedia.org/wiki/WebSockets" rel="nofollow">WebSocket on Wikipedia</a></li><li><a
href="http://net.tutsplus.com/tutorials/javascript-ajax/start-using-html5-websockets-today/" rel="nofollow">Start Using HTML5 WebSockets Today</a></li><li><a
href="http://www.websockets.org" rel="nofollow">WebSockets.org</a></li><li><a
href="http://www.sitepen.com/blog/2010/10/31/dojo-websocket/" rel="nofollow">Dojo WebSocket</a></li><li><a
href="http://cometdaily.com/2010/11/04/state-of-websocket-support/" rel="nofollow">State of WebSocket Support</a></li><li><a
href="http://testsuites.opera.com/websockets/">Opera WebSockets Test Suite</a></li></ul><div
class="actions"><a
href="http://davidwalsh.name/dw-content/websockets.zip" class="demo">View Demo</a><div
class="clear"></div></div><p>Take a moment to download my demo and visit the resources provided above.  The WebSocket API is the future of asynchronous messaging;  Socket.IO is the best available resource for WebSocket in NodeJS and within the browser.  Let me know your thoughts on WebSocket as I&#8217;m curious to know if you&#8217;re as excited as I am by this new API!</p><p><a
href="http://davidwalsh.name/websocket">WebSocket and&nbsp;Socket.IO</a> is a post from: <a
href="http://davidwalsh.name">David Walsh :: Legendary scribbles about JavaScript, HTML5, AJAX, PHP, CSS, and ∞.</a></p> ]]></content:encoded> <wfw:commentRss>http://davidwalsh.name/websocket/feed</wfw:commentRss> <slash:comments>20</slash:comments> </item> <item><title>Supporting the onMessage Event in&#160;MooTools</title><link>http://davidwalsh.name/onmessage</link> <comments>http://davidwalsh.name/onmessage#comments</comments> <pubDate>Thu, 04 Nov 2010 14:14:11 +0000</pubDate> <dc:creator>David Walsh</dc:creator> <category><![CDATA[HTML5]]></category> <category><![CDATA[MooTools]]></category><guid
isPermaLink="false">http://davidwalsh.name/?p=5106</guid> <description><![CDATA[Yesterday I threw some window.postMessage knowledge right in your face.  The cross frame/window/domain technology that is window.postMessage is really interesting and as IE6 and IE7 fade away, window.postMessage will gain more momentum.  In looking to listen to onMessage events with MooTools, I noticed that message events aren&#8217;t  handled properly.  The event type is seen as [...]<p><a
href="http://davidwalsh.name/onmessage">Supporting the onMessage Event in&nbsp;MooTools</a> is a post from: <a
href="http://davidwalsh.name">David Walsh :: Legendary scribbles about JavaScript, HTML5, AJAX, PHP, CSS, and ∞.</a></p> ]]></description> <content:encoded><![CDATA[<p>Yesterday I threw some <a
href="http://davidwalsh.name/window-postmessage">window.postMessage</a> knowledge right in your face.  The cross frame/window/domain technology that is window.postMessage is really interesting and as IE6 and IE7 fade away, window.postMessage will gain more momentum.  In looking to listen to onMessage events with MooTools, I noticed that message events aren&#8217;t  handled properly.  The event type is seen as message but the event.data, event.source, and event.origin aren&#8217;t added to the main-level object &#8212; they&#8217;re relegated to event.event.  It&#8217;s time to fix that using MooTools custom events.</p><h2>The MooTools&nbsp;JavaScript</h2><pre class="js">
Element.NativeEvents.message = 2;
Element.Events.message = {
	base: 'message',
	condition: function(event) {
		//if(event.type == 'message') {
		if(!event.$message_extended) {
			event.data = event.event.data;
			event.source = event.event.source;
			event.origin = event.event.origin;
			event.$message_extended = true;
		}
		return true;
	}
};
</pre><p>Regardless of whether or not the event type is within the Element.NativeEvents.message object, its value always matches what&#8217;s provided by the browser, minus the &#8220;on&#8221; prefix.  With that in mind, creating a &#8220;custom&#8221; message event with &#8220;message&#8221; as the base is the way to go.  The condition portion of the custom event is met by the type being &#8220;message,&#8221; so the only check is that the event hasn&#8217;t been handled already.  If the condition is met, I move references to the data, origin, and source to the event object&#8217;s first level to mimic the tradition message event. As an added bonus, if existing properties are undefined, I set their value to false.</p><p>The power of custom MooTools events is awesome.  window.onMessage is rarely used due to IE6 and IE7&#8242;s crap and the lack of use case so onMessage may not be worth adding the code to Core.  If you do, however, need this functionality&#8230;here you go!</p><p><a
href="http://davidwalsh.name/onmessage">Supporting the onMessage Event in&nbsp;MooTools</a> is a post from: <a
href="http://davidwalsh.name">David Walsh :: Legendary scribbles about JavaScript, HTML5, AJAX, PHP, CSS, and ∞.</a></p> ]]></content:encoded> <wfw:commentRss>http://davidwalsh.name/onmessage/feed</wfw:commentRss> <slash:comments>2</slash:comments> </item> <item><title>HTML5&#8242;s async Script&#160;Attribute</title><link>http://davidwalsh.name/html5-async</link> <comments>http://davidwalsh.name/html5-async#comments</comments> <pubDate>Wed, 22 Sep 2010 13:31:00 +0000</pubDate> <dc:creator>David Walsh</dc:creator> <category><![CDATA[HTML5]]></category><guid
isPermaLink="false">http://davidwalsh.name/?p=5075</guid> <description><![CDATA[One of the big reasons I&#8217;me excited about HMTL5 is that features are being implemented that have been long overdue.  We&#8217;ve been using placeholders forever but we&#8217;ve needed to use JavaScript to do it.  We&#8217;ve been making entire blocks clickable like links but we&#8217;ve needed to use JavaScript to do it.  WebKit recently implemented HTML5&#8242;s [...]<p><a
href="http://davidwalsh.name/html5-async">HTML5&#8242;s async Script&nbsp;Attribute</a> is a post from: <a
href="http://davidwalsh.name">David Walsh :: Legendary scribbles about JavaScript, HTML5, AJAX, PHP, CSS, and ∞.</a></p> ]]></description> <content:encoded><![CDATA[<p><img
src="http://davidwalsh.name/dw-content/async.jpg" alt="HTML5 Async Script" /></p><p>One of the big reasons I&#8217;me excited about HMTL5 is that features are being implemented that have been long overdue.  We&#8217;ve been using <a
href="http://davidwalsh.name/html5-placeholder">placeholders</a> forever but we&#8217;ve needed to use JavaScript to do it.  We&#8217;ve been making entire blocks clickable like links but we&#8217;ve needed to use JavaScript to do it.  WebKit recently implemented HTML5&#8242;s <code>async</code> attribute for SCRIPT tags.  We&#8217;ve been accomplishing this task with a variety of JavaScript hacks but this new attribute will allow us to prevent blocking in an easy way.</p><h2>async &#8211; The&nbsp;HTML</h2><p>As I mentioned above, it&#8217;s as easy as adding an attribute:</p><pre class="html">
&lt;script async src="siteScript.js" onload="myInit()"&gt;&lt;/script&gt;
</pre><p>The truth is that if you write your JavaScript effectively, you&#8217;ll use the <code>async</code> attribute to 90% of your SCRIPT elements.</p><h2>defer &#8211; The&nbsp;HTML</h2><p>Safari has also added a <code>defer</code> attribute:</p><pre class="html">
&lt;script defer src="siteScript.js" onload="myInit()"&gt;&lt;/script&gt;
</pre><p>Very similar to the <code>async</code> assignment.</p><h2>async &amp; defer &#8211; What&#8217;s the&nbsp;Difference</h2><p><a
href="http://webkit.org/blog/1395/running-scripts-in-webkit/" rel="nofollow">This WebKit blog post</a> explains the difference between <code>defer</code> and <code>async</code> best:</p><blockquote><p>Both <code>async</code> and <code>defer</code> scripts begin to download immediately without pausing the parser and both support an optional onload handler to address the common need to perform initialization which depends on the script. The difference between <code>async</code> and <code>defer</code> centers around when the script is executed. Each <code>async</code> script executes at the first opportunity after it is finished downloading and before the window’s load event. This means it’s possible (and likely) that <code>async</code> scripts are not executed in the order in which they occur in the page. The <code>defer</code> scripts, on the other hand, are guaranteed to be executed in the order they occur in the page. That execution starts after parsing is completely finished, but before the document’s <code>DOMContentLoaded</code> event.</p></blockquote><h2>Who Supports async and&nbsp;defer?</h2><p>Also from the Safari blog:</p><blockquote><p>In addition to upcoming versions of WebKit-based browsers, Firefox has long supported the defer and onload attributes and support for async was added in version 3.6. Internet Explorer has also long supported the defer attribute. While async is not yet supported, support for the onload attribute was added in version 9.</p></blockquote><h2>async&nbsp;FTW!</h2><p>Seeing that WebKit had implemented <code>async</code> put a huge smile on my face.  Blocking is a huge bottleneck for every website and the ability to easily direct a script to load asynchronously should speed up the web!</p><p><a
href="http://davidwalsh.name/html5-async">HTML5&#8242;s async Script&nbsp;Attribute</a> is a post from: <a
href="http://davidwalsh.name">David Walsh :: Legendary scribbles about JavaScript, HTML5, AJAX, PHP, CSS, and ∞.</a></p> ]]></content:encoded> <wfw:commentRss>http://davidwalsh.name/html5-async/feed</wfw:commentRss> <slash:comments>13</slash:comments> </item> <item><title>HTML5&#8242;s &#8220;email&#8221; and &#8220;url&#8221; Input&#160;Types</title><link>http://davidwalsh.name/html5-email</link> <comments>http://davidwalsh.name/html5-email#comments</comments> <pubDate>Thu, 16 Sep 2010 01:43:57 +0000</pubDate> <dc:creator>David Walsh</dc:creator> <category><![CDATA[HTML5]]></category><guid
isPermaLink="false">http://davidwalsh.name/?p=5071</guid> <description><![CDATA[I&#8217;ve already covered some subtle HTML5 improvements like placeholder, prefetching, and web storage.  Today I want to introduce a few new INPUT element types:  email and url.  Let&#8217;s take a very basic look at these new INPUT types and discuss their advantages. The&#160;Syntax The syntax is as basic as a text input;  instead, you set [...]<p><a
href="http://davidwalsh.name/html5-email">HTML5&#8242;s &#8220;email&#8221; and &#8220;url&#8221; Input&nbsp;Types</a> is a post from: <a
href="http://davidwalsh.name">David Walsh :: Legendary scribbles about JavaScript, HTML5, AJAX, PHP, CSS, and ∞.</a></p> ]]></description> <content:encoded><![CDATA[<p>I&#8217;ve already covered some subtle HTML5 improvements like <a
href="http://davidwalsh.name/html5-placeholder">placeholder</a>, <a
href="http://davidwalsh.name/html5-prefetch">prefetching</a>, and <a
href="http://davidwalsh.name/html5-storage">web storage</a>.  Today I want to introduce a few new INPUT element types:  email and url.  Let&#8217;s take a very basic look at these new INPUT types and discuss their advantages.</p><h2>The&nbsp;Syntax</h2><p>The syntax is as basic as a text input;  instead, you set the type to &#8220;email&#8221; or &#8220;url&#8221;:</p><pre class="html">
&lt;!-- email --&gt;
&lt;input type="email" pattern="[^ @]*@[^ @]*" value=""&gt;

&lt;!-- url --&gt;
&lt;input type="url" value=""&gt;
</pre><p>Using the new HTML5 pattern attribute, you can also provide a regular expression to validate the email  and URL addresses against.  I&#8217;ll save those specifics for another post.</p><h2>The Advantages to Using type=&#8221;email&#8221; and&nbsp;type=&#8221;url&#8221;</h2><p>There are a few advantages to using these special INPUT types:</p><ul><li>You may easily style all email INPUT elements with input[type=email]</li><li>You may easily style all url INPUT elements with input[type=url]</li><li>This INPUT type could be considered more semantically correct.</li><li>Mobile accessibility:  if your user is browsing with an iPhone and they arrive at a special email input, the iPhone will display a keyboard with the @ symbol provided on the primary screen.  If the INPUT is of type &#8220;url&#8221;, the iPhone will display the &#8220;.com&#8221; button on the primary keyboard screen:<br
/><br
/><img
src="http://davidwalsh.name/dw-content/iphone-keyboard.jpg" alt="HTML5 INPUT" /></li></ul><h2>Input on&nbsp;this&#8230;Input&#8230;Type</h2><p>At first I disliked the idea of using different type attribute values per field but after more thought, the accessibility and usability enhancements provided a great boost.  What do you think?</p><p><a
href="http://davidwalsh.name/html5-email">HTML5&#8242;s &#8220;email&#8221; and &#8220;url&#8221; Input&nbsp;Types</a> is a post from: <a
href="http://davidwalsh.name">David Walsh :: Legendary scribbles about JavaScript, HTML5, AJAX, PHP, CSS, and ∞.</a></p> ]]></content:encoded> <wfw:commentRss>http://davidwalsh.name/html5-email/feed</wfw:commentRss> <slash:comments>9</slash:comments> </item> <item><title>HTML5&#8242;s placeholder&#160;Attribute</title><link>http://davidwalsh.name/html5-placeholder</link> <comments>http://davidwalsh.name/html5-placeholder#comments</comments> <pubDate>Mon, 09 Aug 2010 13:58:04 +0000</pubDate> <dc:creator>David Walsh</dc:creator> <category><![CDATA[HTML5]]></category><guid
isPermaLink="false">http://davidwalsh.name/?p=5032</guid> <description><![CDATA[HTML5 has introduced many features to the browser;  some HTML-based, some in the form of JavaScript APIs, but all of them useful.  One of my favorites if the introduction of the placeholder attribute to INPUT elements.  The placeholder attribute shows text in a field until the field is focused upon, then hides the text.  You&#8217;ve [...]<p><a
href="http://davidwalsh.name/html5-placeholder">HTML5&#8242;s placeholder&nbsp;Attribute</a> is a post from: <a
href="http://davidwalsh.name">David Walsh :: Legendary scribbles about JavaScript, HTML5, AJAX, PHP, CSS, and ∞.</a></p> ]]></description> <content:encoded><![CDATA[<p>HTML5 has introduced many features to the browser;  some HTML-based, some in the form of JavaScript APIs, but all of them useful.  One of my favorites if the introduction of the <code>placeholder</code> attribute to INPUT elements.  The <code>placeholder</code> attribute shows text in a field until the field is focused upon, then hides the text.  You&#8217;ve seen this technique a billion times with JavaScript, but native HTML5 support is even better!</p><div
class="actions"><a
href="http://davidwalsh.name/dw-content/html5-placeholder.php" class="demo">View Demo</a><div
class="clear"></div></div><h2>The&nbsp;HTML</h2><pre class="html">
<input type="text" name="first_name" placeholder="Your first name..." />
</pre><p>You&#8217;ll notice that all you need to do is add a <code>placeholder</code> attribute with the generic text of your choice.  Nice that you don&#8217;t need JavaScript to create this effect, huh?</p><h2>Checking for Placeholder&nbsp;Support</h2><p>Since <code>placeholder</code> is a new capability, it&#8217;s important to check for support in the user&#8217;s browser:</p><pre class="js">
function hasPlaceholderSupport() {
	var input = document.createElement('input');
	return ('placeholder' in input);
}
</pre><p>If the user&#8217;s browser doesn&#8217;t support the <code>placeholder</code> feature, you will need to employ a fallback with MooTools, Dojo, or the JavaScript toolkit of your choice:</p><pre class="js">
/* mootools ftw! */
var firstNameBox = $('first_name'),
	message = firstNameBox.get('placeholder');
firstNameBox.addEvents({
	focus: function() {
		if(firstNameBox.value == message) { searchBox.value = ''; }
	},
	blur: function() {
		if(firstNameBox.value == '') { searchBox.value = message; }
	}
});
</pre><div
class="actions"><a
href="http://davidwalsh.name/dw-content/html5-placeholder.php" class="demo">View Demo</a><div
class="clear"></div></div><p><code>placeholder</code> is another great addition to the browser and replaces the oldest snippet of JavaScript in the book!  You can event <a
href="http://davidwalsh.name/html5-placeholder-css">style HTML5 placeholders</a>!</p><p><a
href="http://davidwalsh.name/html5-placeholder">HTML5&#8242;s placeholder&nbsp;Attribute</a> is a post from: <a
href="http://davidwalsh.name">David Walsh :: Legendary scribbles about JavaScript, HTML5, AJAX, PHP, CSS, and ∞.</a></p> ]]></content:encoded> <wfw:commentRss>http://davidwalsh.name/html5-placeholder/feed</wfw:commentRss> <slash:comments>21</slash:comments> </item> <item><title>HTML5:  Wrap Block-Level Elements with&#160;A&#8217;s</title><link>http://davidwalsh.name/html5-elements-links</link> <comments>http://davidwalsh.name/html5-elements-links#comments</comments> <pubDate>Mon, 26 Jul 2010 16:39:56 +0000</pubDate> <dc:creator>David Walsh</dc:creator> <category><![CDATA[HTML5]]></category><guid
isPermaLink="false">http://davidwalsh.name/?p=5018</guid> <description><![CDATA[HTML5 presents a simpler line of thought with HTML than XHTML.  And quite honestly, it&#8217;s a much needed simplification.  One of those simplifications is the ability to wrap block-level elements like DIVs, H-tags, and P&#8216;s with basic A elements.  You read that correctly:  wrap block-level elements with A tags. HTML5&#160;Code &#60;body&#62; &#60;a href="/about-page.php"&#62; &#60;div class="article"&#62; [...]<p><a
href="http://davidwalsh.name/html5-elements-links">HTML5:  Wrap Block-Level Elements with&nbsp;A&#8217;s</a> is a post from: <a
href="http://davidwalsh.name">David Walsh :: Legendary scribbles about JavaScript, HTML5, AJAX, PHP, CSS, and ∞.</a></p> ]]></description> <content:encoded><![CDATA[<p>HTML5 presents a simpler line of thought with HTML than XHTML.  And quite honestly, it&#8217;s a much needed simplification.  One of those simplifications is the ability to wrap block-level elements like <code>DIV</code>s, H-tags, and <code>P</code>&#8216;s with basic <code>A</code> elements.  You read that correctly:  wrap block-level elements with <code>A</code> tags.</p><h2>HTML5&nbsp;Code</h2><pre class="html">
&lt;body&gt;
	&lt;a href="/about-page.php"&gt;
		&lt;div class="article"&gt;
			&lt;h1&gt;About David Walsh&lt;/h1&gt;
			&lt;p&gt;
				I'm a 27 year old Web Developer and jQuery &amp; MooTools Consultant working from Madison, Wisconsin. I am Founder and Lead Developer for Wynq Web Labs. I don't design the websites, I just make them work.
			&lt;/p&gt;
		&lt;/div&gt;
	&lt;/a&gt;
&lt;/body&gt;
</pre><p>There you have it.  A simple A element wrapping <code>DIV</code>s, <code>H1</code>&#8216;s, and <code>P</code>&#8216;s.  Note that you may <em>not</em> wrap <code>A</code> elements with larger <code>A</code> elements.</p><h2>What Do You&nbsp;Think?</h2><p>I have mixed feelings about wrapping block-level elements with A tags.  Taking a quick look at the HTML makes me feel as though the code is dirty or wrong.  On the flip side, we&#8217;ve been using JavaScript to skirt around doing this for a long time.  My <a
href="http://davidwalsh.name/js/clickables">Clickables</a> class aims to accomplish this task.  Using HTML to make something clickable is more natural and doesn&#8217;t require JavaScript.  I guess my question is:  how do you feel about this practice?  Will you use it right away?  Please share!</p><p><a
href="http://davidwalsh.name/html5-elements-links">HTML5:  Wrap Block-Level Elements with&nbsp;A&#8217;s</a> is a post from: <a
href="http://davidwalsh.name">David Walsh :: Legendary scribbles about JavaScript, HTML5, AJAX, PHP, CSS, and ∞.</a></p> ]]></content:encoded> <wfw:commentRss>http://davidwalsh.name/html5-elements-links/feed</wfw:commentRss> <slash:comments>41</slash:comments> </item> </channel> </rss>
<!-- Performance optimized by W3 Total Cache. Learn more: http://www.w3-edge.com/wordpress-plugins/

Minified using disk: basic
Page Caching using disk: enhanced (User agent is rejected)
Database Caching 1/68 queries in 0.064 seconds using disk: basic
Object Caching 1425/1534 objects using disk: basic

Served from: davidwalsh.name @ 2012-02-09 01:02:35 -->
