<?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; jQuery</title> <atom:link href="http://davidwalsh.name/tutorials/jquery/feed" rel="self" type="application/rss+xml" /><link>http://davidwalsh.name</link> <description>Legendary scribbles about JavaScript, HTML5, AJAX, PHP, CSS, and ∞.</description> <lastBuildDate>Sun, 20 May 2012 22:40:48 +0000</lastBuildDate> <language>en</language> <sy:updatePeriod>hourly</sy:updatePeriod> <sy:updateFrequency>1</sy:updateFrequency> <generator>http://wordpress.org/?v=3.3.2</generator> <item><title>Face Detection with&#160;jQuery</title><link>http://davidwalsh.name/face-detection-jquery</link> <comments>http://davidwalsh.name/face-detection-jquery#comments</comments> <pubDate>Thu, 20 Oct 2011 15:54:13 +0000</pubDate> <dc:creator>David Walsh</dc:creator> <category><![CDATA[JavaScript]]></category> <category><![CDATA[jQuery]]></category><guid
isPermaLink="false">http://davidwalsh.name/?p=5317</guid> <description><![CDATA[I&#8217;ve always been intrigued by recognition software because I cannot imagine the logic that goes into all of the algorithms. Whether it&#8217;s voice, face, or other types of detection, people look and sound so different, pictures are shot differently, and from different angles, I cannot fathom how it&#8217;s all done. Since I already covered booby [...]<p><a
href="http://davidwalsh.name/face-detection-jquery">Face Detection with&nbsp;jQuery</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[<a
href="http://davidwalsh.name/dw-content/face-recognition.php"><img
src="http://davidwalsh.name/dw-content/face-detection.png" alt="jQuery Face Detection" class="image" /></a><p>I&#8217;ve always been intrigued by recognition software because I cannot imagine the logic that goes into all of the algorithms.  Whether it&#8217;s voice, face, or other types of detection, people look and sound so different, pictures are shot differently, and from different angles, I cannot fathom how it&#8217;s all done.  Since I already covered <del>booby</del> <a
href="http://davidwalsh.name/nudejs">nudity detection with JavaScript</a>, I thought it would be worth some time to explore face detection.  Facebook uses it, so maybe it has application in your websites.</p><p>One face detection library I found is <a
href="https://github.com/jaysalvat/jquery.facedetection">Face Detection by Jay Salvat</a> and Liu Liu.  This is a standard jQuery plugin that receives an image and returns an array of coordinates of faces found within the image.  Let&#8217;s have a look at how to use it!</p><div
class="actions"><a
href="http://davidwalsh.name/dw-content/face-recognition.php" class="demo">View Demo</a><div
class="clear"></div></div><h2>jQuery.faceDetection</h2><p>Four JS files are required for this jQuery plugin:</p><pre class="html">
%MINIFYHTML9c753ecfc098e93527015aeb22d399880%%MINIFYHTML9c753ecfc098e93527015aeb22d399881%%MINIFYHTML9c753ecfc098e93527015aeb22d399882%%MINIFYHTML9c753ecfc098e93527015aeb22d399883%</pre><p>The faceDetection plugin wraps functionality within the first two JavaScript files, and returns an array of objects which represent the coordinates of the faces within the photo (if any are found).  An example would be:</p><pre class="js">
var coords = jQuery("#myImage").faceDetection();
/* Returns:
	{
		x: 525
		y: 435,
		width: 144,
		height: 144,
		positionX: 532.6353328125226,
		positionY: 443.240976080536,
		offsetX: 532.6353328125226,
		offsetY: 443.240976080536,
		confidence: 12.93120119,
		neighbour: undefined,
	}
*/
</pre><p>You may also add event callbacks to every call:</p><pre class="js">
var coords = jQuery("#myImage").faceDetection({
	complete: function(image, coords) {
		// Do something
	},
	error: function() {
		console.warn("Could not process image");
	}
});
</pre><p>It&#8217;s up to you what you&#8217;d like to do when the faces have been found.  You could add a square around the person&#8217;s face:</p><pre class="js">
jQuery("img").each(function() {
	var img = this;
	// Get faces cooridnates
	var coordinates = jQuery(img).faceDetection();
	// Make boxes if faces are found
	if(coordinates.length) {
		coordinates.forEach(function(coord) {
			jQuery("<div>", {
				css: {
					position: "absolute",
					left: coord.positionX + 5 + "px",
					top: coord.positionY + 5 + "px",
					width: coord.width + "px",
					height: coord.height + "px",
					border: "3px solid white"
				}
			}).appendTo(img.parentNode);
		});
	}
});
</pre><p>There&#8217;s not much more to it than that!</p><div
class="actions"><a
href="http://davidwalsh.name/dw-content/face-recognition.php" class="demo">View Demo</a><div
class="clear"></div></div><p>I tried to vary the photos I used faceDetection on and as I expected, the results are the not perfect.  They are, however, quite good;  no software will be perfect for all cases.  The software also does not do facial comparison, so you would need to provide suggestions as to the face&#8217;s identity via another method.  For what this plugin is meant to do, however, it does pretty well.  I encourage you to give this a try!</p><p><a
href="http://davidwalsh.name/face-detection-jquery">Face Detection with&nbsp;jQuery</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/face-detection-jquery/feed</wfw:commentRss> <slash:comments>13</slash:comments> </item> <item><title>jQuery Chosen&#160;Plugin</title><link>http://davidwalsh.name/jquery-chosen</link> <comments>http://davidwalsh.name/jquery-chosen#comments</comments> <pubDate>Mon, 08 Aug 2011 13:29:44 +0000</pubDate> <dc:creator>David Walsh</dc:creator> <category><![CDATA[jQuery]]></category><guid
isPermaLink="false">http://davidwalsh.name/?p=5277</guid> <description><![CDATA[Without a doubt, my least favorite form element is the SELECT element.  The element is almost unstylable, looks different across platforms, has had inconsistent value access, and disaster that is the result of multiple=true is, well, a disaster.  Needless to say, whenever a developer goes the extra mile to offer solution to these issues, a [...]<p><a
href="http://davidwalsh.name/jquery-chosen">jQuery Chosen&nbsp;Plugin</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[<a
href="http://davidwalsh.name/dw-content/jquery-chosen.php"><img
src="http://davidwalsh.name/dw-content/jquery-chosen.png" alt="jQuery Chosen Plugin" class="image" /></a><p>Without a doubt, my least favorite form element is the <code>SELECT</code> element.  The element is almost unstylable, looks different across platforms, has had inconsistent value access, and disaster that is the result of <code>multiple=true</code> is, well, a disaster.  Needless to say, whenever a developer goes the extra mile to offer solution to these issues, a big smile gets painted on my face.  <a
href="http://www.getharvest.com/">Harvest</a> recently released Chosen, a <code>SELECT</code> enhancer which offers autosuggest, search, stylability, and an elegant solution for multiple selection.  Better yet, Chosen is available for both jQuery and Prototype.  Let&#8217;s take a look at how to use Chosen!</p><div
class="actions"><a
href="http://davidwalsh.name/dw-content/jquery-chosen.php" class="demo">View Demo</a><div
class="clear"></div></div><h2>The&nbsp;HTML</h2><p>Chosen uses true <code>SELECT</code> elements as the base for its construction, so create your <code>SELECT</code> and <code>OPTION</code> elements as usual:</p><pre class="html">
&lt;!-- single dropdown --&gt;
&lt;select class="chosen" style="width:200px;"&gt;
	&lt;option&gt;Choose...&lt;/option&gt;
	&lt;option&gt;jQuery&lt;/option&gt;
	&lt;option selected="selected"&gt;MooTools&lt;/option&gt;
	&lt;option&gt;Prototype&lt;/option&gt;
	&lt;option&gt;Dojo Toolkit&lt;/option&gt;
&lt;/select&gt;

&lt;!-- multiple dropdown --&gt;
&lt;select class="chosen" multiple="true" style="width:400px;"&gt;
	&lt;option&gt;Choose...&lt;/option&gt;
	&lt;option&gt;jQuery&lt;/option&gt;
	&lt;option selected="selected"&gt;MooTools&lt;/option&gt;
	&lt;option&gt;Prototype&lt;/option&gt;
	&lt;option selected="selected"&gt;Dojo Toolkit&lt;/option&gt;
&lt;/select&gt;
</pre><p>As expected, Chosen respects the <code>selected</code> attribute and selects the desired values during construction.</p><h2>The jQuery&nbsp;JavaScript</h2><p>The jQuery usage is as you would expect:</p><pre class="js">
jQuery(document).ready(function(){
	jQuery(".chosen").chosen();
});
</pre><p>The plugin detects the multiple designation and creates a Facebook-style display, otherwise creates a standard-looking <code>SELECT</code> element with search capabilities.  Chosen also responds to keyboard commands for selection.  Brilliant!  To change the placeholder text of the given multiple <code>SELECT</code>, update the placeholder data for the given node:</p><pre class="js">
jQuery(document).ready(function(){
	jQuery(".chosen").data("placeholder","Select Frameworks...").chosen();
});
</pre><p>I recommend updating the placeholder as the default &#8220;Select Some Options&#8221; isn&#8217;t the most pleasing of messages.</p><div
class="actions"><a
href="http://davidwalsh.name/dw-content/jquery-chosen.php" class="demo">View Demo</a><div
class="clear"></div></div><p>Chosen isn&#8217;t quite perfect;  I&#8217;d like to see a maxSelectedOptions option, and possibly an &#8220;error&#8221; or &#8220;required&#8221; CSS state.  Outside of those small criticisms, I think Chosen is a solid piece of work.  Being offered in both jQuery and Prototype is a bonus for users of both JavaScript frameworks.  If you hate <code>SELECT</code> elements as much as I do, give Chosen a try!</p><p><a
href="http://davidwalsh.name/jquery-chosen">jQuery Chosen&nbsp;Plugin</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/jquery-chosen/feed</wfw:commentRss> <slash:comments>30</slash:comments> </item> <item><title>Event Delegation with MooTools, Dojo, and&#160;jQuery</title><link>http://davidwalsh.name/delegate-event</link> <comments>http://davidwalsh.name/delegate-event#comments</comments> <pubDate>Tue, 15 Mar 2011 14:21:02 +0000</pubDate> <dc:creator>David Walsh</dc:creator> <category><![CDATA[Dojo]]></category> <category><![CDATA[JavaScript]]></category> <category><![CDATA[jQuery]]></category> <category><![CDATA[MooTools]]></category><guid
isPermaLink="false">http://davidwalsh.name/?p=5192</guid> <description><![CDATA[I&#8217;ve covered the ins and outs of event delegation within JavaScript a few weeks ago but most developers utilize JavaScript frameworks so I thought I&#8217;d take a few moments to show you how to implement this wonderful event strategy with the MooTools, Dojo, and jQuery JavaScript frameworks. The MooTools&#160;JavaScript The Element.Delegation class with MooTools More [...]<p><a
href="http://davidwalsh.name/delegate-event">Event Delegation with MooTools, Dojo, and&nbsp;jQuery</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 covered the ins and outs of <a
href="http://davidwalsh.name/event-delegate">event delegation</a> within JavaScript a few weeks ago but most developers utilize JavaScript frameworks so I thought I&#8217;d take a few moments to show you how to implement this wonderful event strategy with the MooTools, Dojo, and jQuery JavaScript frameworks.</p><h2>The MooTools&nbsp;JavaScript</h2><p>The <a
href="http://mootools.net/docs/more/Element/Element.Delegation">Element.Delegation class with MooTools More</a> allows for developers to user event delegation within their application.  The syntax looks very much like MooTools&#8217; Event class&#8217; addEvent method with the exception that the :relay pseudo allows you to provide an argument which represents the elements which should answer to delegation:</p><pre class="js">
// link-list is the parent, a is the child elements
document.id("link-list").addEvent("click:relay(a)", function(event,node){
	console.log("you clicked a link!",node);
});
</pre><p>The MooTools team used addEvent with the custom relay method to make adding event delegation to nodes very much like native event assignment.  I hope you like it!</p><h2>The jQuery&nbsp;JavaScript</h2><p>jQuery uses the intelligently named <a
href="http://api.jquery.com/delegate/">delegate method</a> for event delegation:</p><pre class="js">
$("#link-list").delegate("a", "click", function(){
	// "$(this)" is the node that was clicked
	console.log("you clicked a link!",$(this));
});
</pre><p>The delegate method accepts three arguments:  the selector to be matched, the event to be responded to, and the callback with which to run for the given node.</p><h2>The Dojo&nbsp;JavaScript</h2><p>The Dojo Toolkit&#8217;s event delegation capabilities live within the dojox.NodeList.delegate resource.  Much like jQuery, Dojo uses the delegate method for event delegation:</p><pre class="js">
// Require the resource
dojo.require("dojox.NodeList.delegate");

// *Sigh* When the DOM is ready...
dojo.ready(function() {
	// Assign an event
	dojo.query("#link-list").delegate("a","onclick",function(event) {
		// "this.node" is the node that was clicked
		console.log("you clicked a link!",this);
	});
});
</pre><p>The delegate method accepts the same arguments as jQuery:  selector, event type, and callback.</p><p>Event delegation is especially useful for applications which dynamically create and remove DOM nodes.  Imagine the nightmare in having to assign events frequently (to new nodes) and remove events from deleted nodes (to prevent IE memory leaks).  Take full advantage of the delegation capabilities of each framework &#8212; they&#8217;ll come in use quickly!</p><p><a
href="http://davidwalsh.name/delegate-event">Event Delegation with MooTools, Dojo, and&nbsp;jQuery</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/delegate-event/feed</wfw:commentRss> <slash:comments>17</slash:comments> </item> <item><title>JSONP with jQuery, MooTools, and&#160;Dojo</title><link>http://davidwalsh.name/jsonp</link> <comments>http://davidwalsh.name/jsonp#comments</comments> <pubDate>Mon, 28 Feb 2011 15:09:42 +0000</pubDate> <dc:creator>David Walsh</dc:creator> <category><![CDATA[APIs]]></category> <category><![CDATA[Dojo]]></category> <category><![CDATA[jQuery]]></category> <category><![CDATA[MooTools]]></category><guid
isPermaLink="false">http://davidwalsh.name/?p=5181</guid> <description><![CDATA[We all know that the big limitation of AJAX is that cross-domain requests aren&#8217;t allowed.  We also know, however, that we skirt around that rule a bit by using JSONP.  JSONP is the process of SCRIPT tag injection, referencing a cross-domain URL and providing a callback function (on your page) that the provider will call [...]<p><a
href="http://davidwalsh.name/jsonp">JSONP with jQuery, MooTools, and&nbsp;Dojo</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[<img
src="http://davidwalsh.name/dw-content/jsonp.png" alt="JSONP MooTools jQuery" class="image" /><p>We all know that the big limitation of AJAX is that cross-domain requests aren&#8217;t allowed.  We also know, however, that we skirt around that rule a bit by using JSONP.  JSONP is the process of SCRIPT tag injection, referencing a cross-domain URL and providing a callback function (on your page) that the provider will call so that you can handle the result.  Let&#8217;s take a look at how JSONP is handled with jQuery, MooTools, and the Dojo Toolkit.  For our examples, we&#8217;ll pull tweets from Twitter with the term &#8220;Arsenal&#8221; in them.</p><h2>jQuery&nbsp;JSONP</h2><p>jQuery uses the same method for JSONP as it does for regular JSON &#8212; the <a
href="http://api.jquery.com/jQuery.getJSON/">jQuery.getJSON</a> method:</p><pre class="js">
jQuery.getJSON("http://search.twitter.com/search.json?callback=?",{
	q: "Arsenal"
},function(tweets) {
	// Handle response here
	console.info("Twitter returned: ",tweets);
});
</pre><p>As long as a callback parameter is provided to the getJSON method, jQuery will consider the request JSONP.</p><h2>MooTools&nbsp;JSONP</h2><p>MooTools requires the <a
href="http://mootools.net/docs/more/Request/Request.JSONP">Request.JSONP Class</a> available in <a
href="http://mootools.net/more/">MooTools More</a>.  Armed with Request.JSONP, fetching JSON from another domain is a piece of cake:</p><pre class="js">
new Request.JSONP({
	url: "http://search.twitter.com/search.json",
	data: {
		q: "Arsenal"
	},
	onComplete: function(tweets) {
		// Log the result to console for inspection
		console.info("Twitter returned: ",tweets);
	}
}).send();
</pre><p>Request.JSONP is a super compact class too!</p><h2>Dojo&nbsp;JSONP</h2><p>JSONP with the Dojo Toolkit requires the <a
href="http://dojotoolkit.org/reference-guide/dojo/io/script.html">dojo.io.script</a> resource and its get method:</p><pre class="js">
// dojo.io.script is an external dependency, so it must be required
dojo.require("dojo.io.script");

// When the resource is ready
dojo.ready(function() {
	
	// Use the get method
	dojo.io.script.get({
		// The URL to get JSON from Twitter
		url: "http://search.twitter.com/search.json",
		// The callback paramater
		callbackParamName: "callback", // Twitter requires "callback"
		// The content to send
		content: {
			q: "Arsenal"
		},
		// The success callback
		load: function(tweetsJson) {  // Twitter sent us information!
			// Log the result to console for inspection
			console.info("Twitter returned: ",tweetsJson);
		}
	});
});
</pre><p>Retrieving JSON with Dojo is usually done with the dojo.xhrGet method, but JSONP request this special method.  The arguments for dojo.io.script.get are the same as dojo.xhrGet with the exception of the callback parameter.</p><p>JSONP is a hugely effective, reliable, and easy to implement.  JSONP strategies also allow developers to avoid cumbersome server-side proxy writing to retrieve data.  Each of the JavaScript libraries above have battle-tested methods for retrieving JSON data across domains &#8212; it&#8217;s up to you to implement them to suit your needs!</p><p><a
href="http://davidwalsh.name/jsonp">JSONP with jQuery, MooTools, and&nbsp;Dojo</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/jsonp/feed</wfw:commentRss> <slash:comments>10</slash:comments> </item> <item><title>Create an Exploding Logo with CSS3 and MooTools or&#160;jQuery</title><link>http://davidwalsh.name/css-explode</link> <comments>http://davidwalsh.name/css-explode#comments</comments> <pubDate>Tue, 25 Jan 2011 15:15:05 +0000</pubDate> <dc:creator>David Walsh</dc:creator> <category><![CDATA[Browsers]]></category> <category><![CDATA[CSS]]></category> <category><![CDATA[jQuery]]></category> <category><![CDATA[MooTools]]></category><guid
isPermaLink="false">http://davidwalsh.name/?p=5157</guid> <description><![CDATA[When MooTools contributor and moo4q creator Ryan Florence first showed me his outstanding CSS animation post, I was floored.  His exploding text effect is an amazing example of the power of CSS3 and a dash of JavaScript.   I wanted to implement this effect on my new blog redesign but with a bit more pop, [...]<p><a
href="http://davidwalsh.name/css-explode">Create an Exploding Logo with CSS3 and MooTools or&nbsp;jQuery</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[<a
href="http://davidwalsh.name/dw-content/explode-css.php"><img
src="http://davidwalsh.name/dw-content/explodingLogo.png" alt="CSS Animation" class="image" /></a><p>When <a
href="http://ryanflorence.com/">MooTools contributor and moo4q</a> creator Ryan Florence first showed me his <a
href="http://ryanflorence.com/cssanimation/">outstanding CSS animation post</a>, I was floored.  His exploding text effect is an amazing example of the power of CSS3 and a dash of JavaScript.   I wanted to implement this effect on my new blog redesign but with a bit more pop, so I wrote some MooTools code to take static image and make it an animated, exploding masterpiece.  Let me show you how I did it, and as a bonus, I&#8217;m created a snippet of jQuery that accomplishes the same effect.</p><div
class="actions"> <a
href="http://davidwalsh.name/dw-content/explode-css.php" class="demo">MooTools Demo</a> <a
href="http://davidwalsh.name/dw-content/explode-css.php?jquery" class="demo">jQuery Demo</a><div
class="clear"></div></div><h2>Ryan Florence&#8217;s Animation&nbsp;Library</h2><p>Ryan&#8217;s CSS animation library, available with vanilla JavaScript, MooTools, or jQuery, and can only be described as a fucking work of art.  His animation library is mobile-enabled, works a variety of A-grade browsers, and is very compact.  Download and study <a
href="http://ryanflorence.com/cssanimation/">Ryan&#8217;s animation library</a> before proceeding with this post.</p><p>Ryan&#8217;s post also features an <em>awesome</em> demo and a few helpful functions.  A few of these functions include:</p><pre class="js">
// reset transforms to this
var zeros = {x:0, y:0, z:0};

// Implement animation methods on the element prototype
Element.implement({
	
	// Scatter elements all over the place
	scatter: function(){
		return this.translate({
			x: Number.random(-1000, 1000),
			y: Number.random(-1000, 1000),
			z: Number.random(-500, 500)
		}).rotate({
			x: Number.random(-720, 720),
			y: Number.random(-720, 720),
			z: Number.random(-720, 720)
		});
	},
	
	// Return them to their original state
	unscatter: function(){ 
		return this.translate(zeros).rotate(zeros);
	},
	
	//  Frighten the image!  AHHHHHHHH!
	frighten: function(d){
		this.setTransition('timing-function', 'ease-out').scatter();
		setTimeout(function(){ 
			this.setTransition('timing-function', 'ease-in-out').unscatter();
		}.bind(this), 500);
		return this;
	},
	
	// Zoooooom into me
	zoom: function(delay){
		var self = this;
		this.scale(0.01);
		setTimeout(function(){
			self.setTransition({
				property: 'transform',
				duration: '250ms',
				'timing-function': 'ease-out'
			}).scale(1.2);
			setTimeout(function(){
				self.setTransition('duration', '100ms').scale(1);
			}, 250)
		}, delay);
	},
	
	// Create a slider
	makeSlider: function(){
		var open = false,
			next = this.getNext(),
			height = next.getScrollSize().y,
			transition = {
				property: 'height',
				duration: '500ms',
				transition: 'ease-out'
			};
		next.setTransition(transition);
		this.addEvent('click', function(){
			next.setStyle('height', open ? 0 : height);
			open = !open;
		});
	},
	
	// Scatter, come back
	fromChaos: (function(x){
		var delay = 0;
		return function(){
			var element = this;
			//element.scatter();
			setTimeout(function(){
				element.setTransition({
					property: 'transform',
					duration: '500ms',
					'timing-function': 'ease-out'
				});
				setTimeout(function(){
					element.unscatter();
					element.addEvents({
						mouseenter: element.frighten.bind(element),
						touchstart: element.frighten.bind(element)
					});
				}, delay += x);
			}, x);
		}
	}())

});
</pre><p>Now let&#8217;s jump on the exploding logo!</p><h2>The&nbsp;HTML</h2><p>The exploding element can be of any type, but for the purposes of this example, we&#8217;ll use an A element with a background image:</p><pre class="html">
&lt;a href="/" id="homeLogo"&gt;David Walsh Blog&lt;/a&gt;
</pre><p>Make sure the element you use is a block element, or styled to be block.</p><h2>The&nbsp;CSS</h2><p>The original element should be styled to size (width and height) with the background image that we&#8217;ll use as the exploding image:</p><pre class="css">
a#homeLogo	{ 
	width:300px; 
	height:233px; 
	text-indent:-3000px; 
	background:url(/wp-content/themes/2k11/images/homeLogo.png) 0 0 no-repeat; 
	display:block; 
	z-index:2; 
}
a#homeLogo span { 
	float:left;
	display:block;
	background-image:url(/wp-content/themes/2k11/images/homeLogo.png); 
	background-repeat:no-repeat;
}
.clear { clear:both; }
</pre><p>Remember to set the text-indent setting so that the link text will not display.  The explosion shards will be JavaScript-generated SPAN elements which are displayed as in block format.  Note that the SPAN has the same background image as the A element &#8212; we&#8217;ll simply modify the background position of the element to act as the piece of the logo that each SPAN represents.</p><h2>The MooTools&nbsp;JavaScript</h2><p>The first step is putting together a few variables we&#8217;ll need to to calculate element dimensions:</p><pre class="js">
// Get the proper CSS prefix from the page
var cssPrefix = false;
switch(Browser.name) { // Implement only for Chrome, Firefox, and Safari
	case "safari":
	case "chrome":
		cssPrefix = "webkit";
		break;
	case "firefox":
		cssPrefix = "moz";
		break;
}

if(cssPrefix) {
	
	// 300 x 233
	var cols = 10; // Desired columns
	var rows = 8; // Desired rows
	var totalWidth = 300; // Logo width
	var totalHeight = 233; // Logo height
	var singleWidth = Math.ceil(totalWidth / cols); // Shard width
	var singleHeight = Math.ceil(totalHeight / rows); // Shard height
	var shards = []; // Array of SPANs
	
</pre><p>You&#8217;ll note that I&#8217;ve explicitly set the number of columns and rows I want.  You don&#8217;t want the shards to be too large or too small, so feel free to experiment.  You could probably use another calculation to get column and row numbers, but I&#8217;ll leave that up to you.</p><p>The next step is looping through each row and column, creating a new SPAN element for each shard.  The background position, width, and height of the SPAN will be calculated with the &#8230; calculations &#8230; we &#8230; calculated &#8230; above.</p><pre class="js">
// Remove the text and background image from the logo
var logo = document.id("homeLogo").set("html","").setStyles({ backgroundImage: "none" });

// For every desired row
rows.times(function(rowIndex) {
	// For every desired column
	cols.times(function(colIndex) {
		// Create a SPAN element with the proper CSS settings
		// Width, height, browser-specific CSS
		var element = new Element("span",{
			style: "width:" + (singleWidth) + "px;height:" + (singleHeight) + "px;background-position:-" + (singleHeight * colIndex) + "px -" + (singleWidth * rowIndex) + "px;-" + cssPrefix + "-transition-property: -" + cssPrefix + "-transform; -" + cssPrefix + "-transition-duration: 200ms; -" + cssPrefix + "-transition-timing-function: ease-out; -" + cssPrefix + "-transform: translateX(0%) translateY(0%) translateZ(0px) rotateX(0deg) rotateY(0deg) rotate(0deg);"
		}).inject(logo);
		// Save it
		shards.push(element);
	});
	// Create a DIV clear for next row
	new Element("div",{ clear: "clear" }).inject(logo);
});
</pre><p>With the SPAN elements, you&#8217;ll note that several CSS3 properties are being set to it, allowing the browser to do its magic.  Using CSS3 is much less resource-consuming within the browser than using JavaScript to do all of the animation.</p><p>The last step is calling the fromChaos method provided by Ryan Florence&#8217;s CSS animation code to set into motion the madness!</p><pre class="js">
// Chaos!
$$(shards).fromChaos(1000);
</pre><p>There you have it!  A completely automated method of exploding an image using CSS3 and MooTools JavaScript!</p><h2>The jQuery&nbsp;JavaScript</h2><p>Ryan also wrote the CSS animation code in jQuery so you can easily create a comparable effect with jQuery!</p><pre class="js">
Number.random = function(min, max){
	return Math.floor(Math.random() * (max - min + 1) + min);
};

var zeros = {x:0, y:0, z:0};

jQuery.extend(jQuery.fn, {

	scatter: function(){
		return this.translate({
			x: Number.random(-1000, 1000),
			y: Number.random(-1000, 1000),
			z: Number.random(-500, 500)
		}).rotate({
			x: Number.random(-720, 720),
			y: Number.random(-720, 720),
			z: Number.random(-720, 720)
		});
	},

	unscatter: function(){ 
		return this.translate(zeros).rotate(zeros);
	},

	frighten: function(d){
		var self = this;
		this.setTransition('timing-function', 'ease-out').scatter();
		setTimeout(function(){
			self.setTransition('timing-function', 'ease-in-out').unscatter();
		}, 500);
		return this;
	},

	zoom: function(delay){
		var self = this;
		this.scale(0.01);
		setTimeout(function(){
			self.setTransition({
				property: 'transform',
				duration: '250ms',
				'timing-function': 'ease-out'
			}).scale(1.2);
			setTimeout(function(){
				self.setTransition('duration', '100ms').scale(1);
			}, 250)
		}, delay);
		return this;
	},

	makeSlider: function(){
		return this.each(function(){
			var $this = $(this),
				open = false,
				next = $this.next(),
				height = next.attr('scrollHeight'),
				transition = {
					property: 'height',
					duration: '500ms',
					transition: 'ease-out'
				};
			next.setTransition(transition);
			$this.bind('click', function(){
				next.css('height', open ? 0 : height);
				open = !open;
			});
		})
	},

	fromChaos: (function(){
		var delay = 0;
		return function(){
			return this.each(function(){
				var element = $(this);
				//element.scatter();
				setTimeout(function(){
					element.setTransition({
						property: 'transform',
						duration: '500ms',
						'timing-function': 'ease-out'
					});
					setTimeout(function(){
						element.unscatter();
						element.bind({
							mouseenter: jQuery.proxy(element.frighten, element),
							touchstart: jQuery.proxy(element.frighten, element)
						});
					}, delay += 100);
				}, 1000);
			})
		}
	}())

});


// When the DOM is ready...
$(document).ready(function() {
	
	// Get the proper CSS prefix
	var cssPrefix = false;
	if(jQuery.browser.webkit) {
		cssPrefix = "webkit";
	}
	else if(jQuery.browser.mozilla) {
		cssPrefix = "moz";
	}
	
	// If we support this browser
	if(cssPrefix) {
		// 300 x 233
		var cols = 10; // Desired columns
		var rows = 8; // Desired rows
		var totalWidth = 300; // Logo width
		var totalHeight = 233; // Logo height
		var singleWidth = Math.ceil(totalWidth / cols); // Shard width
		var singleHeight = Math.ceil(totalHeight / rows); // Shard height
		
		// Remove the text and background image from the logo
		var logo = jQuery("#homeLogo").css("backgroundImage","none").html("");
		
		// For every desired row
		for(x = 0; x &lt; rows; x++) {
			var last;
			//For every desired column
			for(y = 0; y &lt; cols; y++) {
				// Create a SPAN element with the proper CSS settings
				// Width, height, browser-specific CSS
				last = jQuery("&lt;span /&gt;").attr("style","width:" + (singleWidth) + "px;height:" + (singleHeight) + "px;background-position:-" + (singleHeight * y) + "px -" + (singleWidth * x) + "px;-" + cssPrefix + "-transition-property: -" + cssPrefix + "-transform; -" + cssPrefix + "-transition-duration: 200ms; -" + cssPrefix + "-transition-timing-function: ease-out; -" + cssPrefix + "-transform: translateX(0%) translateY(0%) translateZ(0px) rotateX(0deg) rotateY(0deg) rotate(0deg);");
				// Insert into DOM
				logo.append(last);
			}
			// Create a DIV clear for row
			last.append(jQuery("&lt;div /&gt;").addClass("clear"));
		}
		
		// Chaos!
		jQuery("#homeLogo span").fromChaos();
	}
});
</pre><p>Not as beautiful as the MooTools code, of course, but still effective!</p><div
class="actions"> <a
href="http://davidwalsh.name/dw-content/explode-css.php" class="demo">MooTools Demo</a> <a
href="http://davidwalsh.name/dw-content/explode-css.php?jquery" class="demo">jQuery Demo</a><div
class="clear"></div></div><p>And there you have it:  CSS animations, JavaScript, and dynamic effects.  My favorite part of this effect is how little code is involved.  You get a lot of bang with your buck with this.  Of course, using this effect everywhere would surely get groans so use it wisely!</p><p><a
href="http://davidwalsh.name/css-explode">Create an Exploding Logo with CSS3 and MooTools or&nbsp;jQuery</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/css-explode/feed</wfw:commentRss> <slash:comments>28</slash:comments> <series:name><![CDATA[CSS3 Animations]]></series:name> </item> <item><title>Create Spinning, Fading Icons with CSS3 and&#160;jQuery</title><link>http://davidwalsh.name/fade-spin-css3-jquery</link> <comments>http://davidwalsh.name/fade-spin-css3-jquery#comments</comments> <pubDate>Mon, 10 Jan 2011 15:04:32 +0000</pubDate> <dc:creator>David Walsh</dc:creator> <category><![CDATA[CSS]]></category> <category><![CDATA[jQuery]]></category> <category><![CDATA[Markup]]></category><guid
isPermaLink="false">http://davidwalsh.name/?p=5154</guid> <description><![CDATA[Last week I debuted a popular blog post titled Create Spinning, Fading Icons with CSS3 and MooTools. The post detailed how you could leverage CSS3&#8242;s transformations and opacity properties, as well as the magical MooTools JavaScript framework, to create spinning, fading, animated icons.  Due to popular request, I&#8217;ve duplicated the effect with another popular JavaScript toolkit: [...]<p><a
href="http://davidwalsh.name/fade-spin-css3-jquery">Create Spinning, Fading Icons with CSS3 and&nbsp;jQuery</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>Last week I debuted a popular blog post titled <a
title="Create Spinning, Fading Icons with CSS3 and MooTools" href="http://davidwalsh.name/css-spin">Create Spinning, Fading Icons with CSS3 and MooTools</a>.  The post detailed how you could leverage CSS3&#8242;s transformations and opacity properties, as well as the magical MooTools JavaScript framework, to create spinning, fading, animated icons.  Due to popular request, I&#8217;ve duplicated the effect with another popular JavaScript toolkit:  jQuery.</p><div
class="actions"><a
href="http://davidwalsh.name/dw-content/css-animation-jquery.php" class="demo">View Demo</a><div
class="clear"></div></div><h2>The&nbsp;HTML</h2><pre class="html">
&lt;div id="followIcons"&gt;
	&lt;a href="http://feeds2.feedburner.com/Bludice" id="iconRSS"&gt;RSS Feed&lt;/a&gt;
	&lt;a href="http://twitter.com/davidwalshblog" id="iconTwitter"&gt;@davidwalshblog Twitter&lt;/a&gt;
	&lt;a href="http://github.com/darkwing" id="iconGitHub"&gt;@davidwalshblog Twitter&lt;/a&gt;
	&lt;a href="http://del.icio.us/dwizzlestar" id="iconDelicious"&gt;dwizzlestar de.licio.us&lt;/a&gt;
	&lt;a href="http://facebook.com/davidwalsh83" id="iconFacebook"&gt;David Walsh Facebook&lt;/a&gt;
	&lt;a href="http://linkedin.com/in/davidjameswalsh" id="iconLinkedIn"&gt;David Walsh LinkedIn&lt;/a&gt;
	&lt;a href="skype:davidwalsh83?chat" id="iconSkype"&gt;David Walsh Skype&lt;/a&gt;
	&lt;a href="&#109;&#97;&#105;lt&#111;&#58;d&#97;v&#105;&#100;&#64;davi&#100;&#119;&#97;&#108;s&#104;&#46;n&#97;&#109;e" id="iconMail"&gt;David Walsh Email&lt;/a&gt;
	&lt;a href="http://mootools.net/forge/profile/davidwalsh" id="iconForge"&gt;David Walsh MooTools Forge&lt;/a&gt;
&lt;/div&gt;
</pre><p>The links are as standard as they come.  These will be turned into dynamic icons.</p><h2>The&nbsp;CSS</h2><p>The first part of the process is using standard CSS to move the text off screen and instead use the icons as background images for the link:</p><pre class="css">#followIcons a	{
display:inline-block;
width:48px;
height:48px;
text-indent:-3000px;
background-position:0 0;
background-repeat:no-repeat;
z-index:2000;
overflow:hidden;
position:absolute;
}</pre><p>Once we&#8217;ve done that time-tested practice, it&#8217;s time to put a few initial CSS3 settings into place.  As you probably know, at this point all CSS transform properties are browser-specific, so our CSS will get a bit lengthy:</p><pre class="css">#followIcons a	{
-webkit-transition-duration: 0.8s;
-moz-transition-duration: 0.8s;
-o-transition-duration: 0.8s;
transition-duration: 0.8s;
-webkit-transition-property: -webkit-transform;
-moz-transition-property: -moz-transform;
-o-transition-property: -o-transform;
transition-property: transform;
}</pre><p>The transition duration will be 0.8 seconds and transition property will be a basic transform.  You can change the transform duration to any duration you&#8217;d like.  Too fast or too slow will ruin the effect <em>(that&#8217;s what she said)</em>.</p><h2>The jQuery&nbsp;JavaScript</h2><p>The first part is randomly positioning each node/icon within the container.  It&#8217;s important to know the container&#8217;s width and height, then subtract the icon width and height from that to know the true area you can fit the icon into.  Nothing would be more lame than a piece of the icon hidden. The next step of the process is adding mouseenter and mouseleave events to make the images rotate and fade in during each respective event.</p><pre class="js">
jQuery(document).ready(function() {

	// "Globals" - Will make things compress mo-betta
	var $random = function(x) { return Math.random() * x; };
	var availableWidth = 400, availableHeight = 40;
	
	// Get the proper CSS prefix
	if(jQuery.browser.webkit) {
		cssPrefix = "webkit";
	}
	else if(jQuery.browser.mozilla) {
		cssPrefix = "moz";
	}
	else if(jQuery.browser.opera) {
		cssPrefix = "o";
	}

	// Apply opacity
	var zIndex = 1000;
	
	// Randomize each link
	jQuery.each(jQuery("#followIcons a"),function(index) {
		var startDeg = $random(360);
		var element = jQuery(this);
		var resetPlace = function() {
			element.fadeTo(250,0.6).css("-" + cssPrefix + "-transform","rotate(" + startDeg + "deg)");
		};
		element.attr("style","top:" + $random(availableHeight) + "px; left:" + $random(availableWidth) + "px; z-index:" + zIndex).hover(function() {
			element.fadeTo(250,1).css("zIndex",++zIndex).css("-" + cssPrefix + "-transform","rotate(0deg)");
		},resetPlace);
		resetPlace();
	});
	
});
</pre><p>When the mouseenter event occurs, the rotation is animated to 0, no rotation.  When the mouse leaves the element, the element animates to its initial random rotation.  You&#8217;ll also note that I&#8217;ve used opacity to add to the subtle effect.</p><div
class="actions"><a
href="http://davidwalsh.name/dw-content/css-animation-jquery.php" class="demo">View Demo</a><div
class="clear"></div></div><p>There you have it!</p><p><a
href="http://davidwalsh.name/fade-spin-css3-jquery">Create Spinning, Fading Icons with CSS3 and&nbsp;jQuery</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/fade-spin-css3-jquery/feed</wfw:commentRss> <slash:comments>19</slash:comments> </item> <item><title>Create Spinning, Fading Icons with CSS3 and&#160;MooTools</title><link>http://davidwalsh.name/css-spin</link> <comments>http://davidwalsh.name/css-spin#comments</comments> <pubDate>Thu, 06 Jan 2011 14:44:50 +0000</pubDate> <dc:creator>David Walsh</dc:creator> <category><![CDATA[Browsers]]></category> <category><![CDATA[CSS]]></category> <category><![CDATA[jQuery]]></category> <category><![CDATA[MooTools]]></category><guid
isPermaLink="false">http://davidwalsh.name/?p=5150</guid> <description><![CDATA[A goal of my latest blog redesign was to practice what I preached a bit more;  add a bit more subtle flair.  One of the ways I accomplished that was by using CSS3 animations to change the display of my profile icons (RSS, GitHub, etc.)  I didn&#8217;t want to abandon CSS animations completely though;  I [...]<p><a
href="http://davidwalsh.name/css-spin">Create Spinning, Fading Icons with CSS3 and&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>A goal of my latest blog redesign was to practice what I preached a bit more;  add a bit more subtle flair.  One of the ways I accomplished that was by using CSS3 animations to change the display of my profile icons (RSS, GitHub, etc.)  I didn&#8217;t want to abandon CSS animations completely though;  I added a bit of MooTools to randomize the icon&#8217;s initial display position and rotation.  Let me show you how to use CSS3 and MooTools to create dymanic, rotating elements.</p><div
class="actions"><a
href="http://davidwalsh.name/dw-content/css-animation.php" class="demo">View Demo</a><div
class="clear"></div></div><h2>The&nbsp;HTML</h2><p>We&#8217;ll use the standard, accessible, SEO-friendly HTML for link creation:</p><pre class="html">
&lt;div id="followIcons"&gt;
	&lt;a href="http://feeds2.feedburner.com/Bludice" rel="nofollow" id="iconRSS"&gt;RSS Feed&lt;/a&gt;
	&lt;a href="http://twitter.com/davidwalshblog" rel="nofollow" id="iconTwitter"&gt;@davidwalshblog Twitter&lt;/a&gt;
	&lt;a href="http://github.com/darkwing" rel="nofollow" id="iconGitHub"&gt;@davidwalshblog Twitter&lt;/a&gt;
	&lt;a href="http://del.icio.us/dwizzlestar" rel="nofollow" id="iconDelicious"&gt;dwizzlestar de.licio.us&lt;/a&gt;
	&lt;a href="http://facebook.com/davidwalsh83" rel="nofollow" id="iconFacebook"&gt;David Walsh Facebook&lt;/a&gt;
	&lt;a href="http://linkedin.com/in/davidjameswalsh" rel="nofollow" id="iconLinkedIn"&gt;David Walsh LinkedIn&lt;/a&gt;
	&lt;a href="skype:davidwalsh83?chat" id="iconSkype"&gt;David Walsh Skype&lt;/a&gt;
	&lt;a href="&#109;a&#105;&#108;t&#111;&#58;da&#118;id&#64;d&#97;&#118;&#105;d&#119;&#97;&#108;sh.na&#109;&#101;" id="iconMail"&gt;David Walsh Email&lt;/a&gt;
	&lt;a href="http://mootools.net/forge/profile/davidwalsh" rel="nofollow" id="iconForge"&gt;David Walsh MooTools Forge&lt;/a&gt;
&lt;/div&gt;
</pre><p>CSS will make these links pretty.</p><h2>The&nbsp;CSS</h2><p>The first part of the process is using standard CSS to move the text off screen and instead use the icons as background images for the link:</p><pre class="css">
#followIcons a	{ 
	display:inline-block; 
	width:48px; 
	height:48px; 
	text-indent:-3000px; 
	background-position:0 0; 
	background-repeat:no-repeat; 
	z-index:2000; 
	overflow:hidden; 
	position:absolute;
}
</pre><p>Once we&#8217;ve done that time-tested practice, it&#8217;s time to put a few initial CSS3 settings into place.  As you probably know, at this point all CSS transform properties are browser-specific, so our CSS will get a bit lengthy:</p><pre class="css">
#followIcons a	{ 
	-webkit-transition-duration: 0.8s;
	-moz-transition-duration: 0.8s;
	-o-transition-duration: 0.8s;
	transition-duration: 0.8s;
	-webkit-transition-property: -webkit-transform;
	-moz-transition-property: -moz-transform;
	-o-transition-property: -o-transform;
	transition-property: transform;
}
</pre><p>The transition duration will be 0.8 seconds and transition property will be a basic transform.  You can change the transform duration to any duration you&#8217;d like.  Too fast or too slow will ruin the effect <em>(that&#8217;s what she said)</em>.</p><h2>The MooTools&nbsp;JavaScript</h2><p>The first part is randomly positioning each node/icon within the container.  It&#8217;s important to know the container&#8217;s width and height, then subtract the icon width and height from that to know the true area you can fit the icon into.  Nothing would be more lame than a piece of the icon hidden.  The next step of the process is adding mouseenter and mouseleave events to make the images rotate and fade in during each respective event.</p><pre class="js">
// "Globals" - Will make things compress mo-betta
var $random = function(x) { return Math.random() * x; };
var availableWidth = 200, availableHeight = 40;

// Find the appropriate prefix icon
var cssPrefix = false;
switch(Browser.name) {
	case "safari":
		cssPrefix = "webkit";
		break;
	case "chrome":
		cssPrefix = "webkit";
		break;
	case "firefox":
		cssPrefix = "moz";
		break;
	case "opera":
		cssPrefix = "o";
		break;
	case "ie":
		cssPrefix = "ms";
		break;
}

// The Icons
var icons = $$("#followIcons a");
// Apply opacity
var zIndex = 1000;

// Randomize each link
icons.each(function(element,index) {
	// Generate the random rotation amount
	var startDeg = $random(360);
	// Place the image at the default rotation and opacity
	var resetPlace = function() {
		element.fade(0.6).setStyle("-" + cssPrefix + "-transform","rotate(" + startDeg + "deg)");
	};
	// Randomly position the element
	element.set("style","top:" + $random(availableHeight) + "px; left:" + $random(availableWidth) + "px; z-index:" + zIndex);
	// Rotate the image initially
	resetPlace();
	// Add events
	element.addEvents({
		mouseenter: function() {
			element.fade(1).setStyle("z-index",++zIndex).setStyle("-" + cssPrefix + "-transform","rotate(0deg)");
		},
		mouseleave: resetPlace
	});
});
</pre><p>When the mouseenter event occurs, the rotation is animated to 0, no rotation.  When the mouse leaves the element, the element animates to its initial random rotation.  You&#8217;ll also note that I&#8217;ve used opacity to add to the subtle effect.</p><div
class="actions"><a
href="http://davidwalsh.name/dw-content/css-animation.php" class="demo">View Demo</a><div
class="clear"></div></div><p>And there you have it:  spinning, fading, animated elements.  What&#8217;s the alternative?  Static, boring, traditional icons.  
What do you think?  Too much?  Too little?  Share your ideas!</p><p><a
href="http://davidwalsh.name/css-spin">Create Spinning, Fading Icons with CSS3 and&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/css-spin/feed</wfw:commentRss> <slash:comments>9</slash:comments> </item> <item><title>Duplicate the jQuery Homepage&#160;Tooltips</title><link>http://davidwalsh.name/jquery-tooltips</link> <comments>http://davidwalsh.name/jquery-tooltips#comments</comments> <pubDate>Tue, 31 Aug 2010 13:48:40 +0000</pubDate> <dc:creator>David Walsh</dc:creator> <category><![CDATA[CSS]]></category> <category><![CDATA[jQuery]]></category> <category><![CDATA[Markup]]></category><guid
isPermaLink="false">http://davidwalsh.name/?p=5056</guid> <description><![CDATA[The jQuery homepage has a pretty suave tooltip-like effect as seen below: The amount of jQuery required to duplicate this effect is next to nothing;  in fact, there&#8217;s more CSS than there is jQuery code!  Let&#8217;s explore how we can duplicate jQuery&#8217;s tooltip effect. View Demo The&#160;HTML The overall structure includes a wrapping DIV element [...]<p><a
href="http://davidwalsh.name/jquery-tooltips">Duplicate the jQuery Homepage&nbsp;Tooltips</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>The jQuery homepage has a pretty suave tooltip-like effect as seen below:</p><p><a
href="http://davidwalsh.name/dw-content/jquery-tooltips-jquery.php"><img
src="http://davidwalsh.name/dw-content/jquery-home.png" alt="jQuery Tooltips" /></a></p><p>The amount of jQuery required to duplicate this effect is next to nothing;  in fact, there&#8217;s more CSS than there is jQuery code!  Let&#8217;s explore how we can duplicate jQuery&#8217;s tooltip effect.</p><div
class="actions"><a
href="http://davidwalsh.name/dw-content/jquery-tooltips-jquery.php" class="demo">View Demo</a><div
class="clear"></div></div><h2>The&nbsp;HTML</h2><p>The overall structure includes a wrapping DIV element with each tooltip link featured in a list:</p><pre class="html">
&lt;div id="jq-intro" class="jq-clearfix"&gt;
	&lt;h2&gt;jQuery is a new kind of JavaScript Library.&lt;/h2&gt;
	&lt;p&gt;jQuery is a fast and concise JavaScript Library that simplifies HTML document traversing, event handling, animating, and AJAX interactions for rapid web development. &lt;strong&gt;jQuery is designed to change the way that you write JavaScript.&lt;/strong&gt;&lt;/p&gt;
	&lt;ul class="jq-checkpoints jq-clearfix"&gt;
		&lt;li&gt;&lt;a href="http://docs.jquery.com/Tutorials" title="Lightweight Footprint" class="jq-thickbox"&gt;Lightweight Footprint&lt;/a&gt;
			&lt;div class="jq-checkpointSubhead"&gt;
				&lt;p&gt;About 18KB in size &lt;em&gt;(Minified and Gzipped)&lt;/em&gt;&lt;/p&gt;
			&lt;/div&gt;
		&lt;/li&gt;
		&lt;li&gt;&lt;a href="http://docs.jquery.com/Tutorials" title="CSS3 Compliant" class="jq-thickbox"&gt;CSS3 Compliant&lt;/a&gt;
			&lt;div class="jq-checkpointSubhead"&gt;
				&lt;p&gt;Supports CSS 1-3 selectors and more!&lt;/p&gt;
			&lt;/div&gt;
		&lt;/li&gt;
		&lt;li&gt;&lt;a href="http://docs.jquery.com/Tutorials" title="Cross-browser" class="jq-thickbox"&gt;Cross-browser&lt;/a&gt;
			&lt;div class="jq-checkpointSubhead"&gt;
				&lt;p&gt;IE 6.0+, FF 2+, Safari 3.0+, Opera 9.0+, Chrome&lt;/p&gt;
			&lt;/div&gt;
		&lt;/li&gt;
	&lt;/ul&gt;
&lt;/div&gt;
</pre><p>Note that the UL element has been given a jq-checkpoints CSS class &#8212; we&#8217;ll use that in a selector for both CSS styling and element collection using jQuery.</p><h2>The&nbsp;CSS</h2><p>Like I said&#8230;there&#8217;s more CSS than there will be jQuery code:</p><pre class="css">
#jq-intro 			{ padding-top:1em; width:605px; margin:0 auto; }
#jq-intro h2 		{ font-size:1.9em; font-weight:bold; color:#5DB0E6; line-height:1em; }
#jq-intro h2 span.jq-jquery { float:left; width:81px; height:23px; margin-right:.3em; position:relative; }
#jq-intro h2 span.jq-jquery span { position:absolute; left:-999999px; }
#jq-intro p 		{ clear:both; font-size:1.5em; margin:5px 0; font-weight:normal; line-height:1.6; }
#jq-intro ul 		{ padding:1.5em 0; list-style-type:none; }
#jq-intro li 		{ float:left; font-size:1.4em; }
#jq-intro li a 	{ color:#5DB0E6; font-weight:bold; text-decoration:underline; float:left; padding:0 30px 0 23px; }
#jq-intro li p 	{ font-size:12px; }
#jq-intro li 		{ position:relative; }
div.jq-checkpointSubhead { display:none; position:absolute; width:253px; height:54px; background:url(jquery-tooltip.png) 0 0 no-repeat; top:-1.5em; left:-35%; z-index:100; }
div.jq-checkpointSubhead p { font-size:1em; padding:10px 5px 0 50px; color:#AE0001; font-weight:bold; line-height:1.3em; margin:0; cursor:pointer; }
</pre><p>Most of the CSS is gloss for the overall look.  The important piece is the jq-checkpointSubhead CSS class being positioned absolutely and with an initial display value of none.  That will allow us to use the :hidden selector within jQuery.</p><h2>The jQuery&nbsp;JavaScript</h2><p>And now for the jQuery JavaScript:</p><pre class="js">
jQuery(document).ready(function() {
	var duration = 500;
	jQuery('.jq-checkpoints li').hover(
		function(){ jQuery(this).find('div.jq-checkpointSubhead:hidden').fadeIn(duration); },
		function(){ jQuery(this).find('div.jq-checkpointSubhead:visible').fadeOut(duration); }
	);
});
</pre><p>When the use hovers over the list items, the tooltip for the given list item fades in.  When the user leaves the list item, the tooltip fades out.</p><div
class="actions"><a
href="http://davidwalsh.name/dw-content/jquery-tooltips-jquery.php" class="demo">View Demo</a><div
class="clear"></div></div><p>There you have it.  If you&#8217;re interested in how to do this with out JavaScript frameworks, read my <a
href="http://davidwalsh.name/jquery-homepage-mootools">MooTools</a> and <a
href="http://davidwalsh.name/dojo-tooltips">Dojo</a> tutorials!</p><p><a
href="http://davidwalsh.name/jquery-tooltips">Duplicate the jQuery Homepage&nbsp;Tooltips</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/jquery-tooltips/feed</wfw:commentRss> <slash:comments>7</slash:comments> </item> <item><title>Create a Twitter AJAX Button with MooTools, jQuery, or&#160;Dojo</title><link>http://davidwalsh.name/twitter-button</link> <comments>http://davidwalsh.name/twitter-button#comments</comments> <pubDate>Wed, 25 Aug 2010 03:28:19 +0000</pubDate> <dc:creator>David Walsh</dc:creator> <category><![CDATA[AJAX]]></category> <category><![CDATA[CSS]]></category> <category><![CDATA[Dojo]]></category> <category><![CDATA[jQuery]]></category> <category><![CDATA[Markup]]></category> <category><![CDATA[MooTools]]></category><guid
isPermaLink="false">http://davidwalsh.name/?p=5049</guid> <description><![CDATA[There&#8217;s nothing like a subtle, slick website widget that effectively uses CSS and JavaScript to enhance the user experience.  Of course widgets like that take many hours to perfect, but it doesn&#8217;t take long for that effort to be rewarded with above-average user retention and buzz.  One of the widgets I love is Twitter&#8217;s &#8220;Follow&#8221; [...]<p><a
href="http://davidwalsh.name/twitter-button">Create a Twitter AJAX Button with MooTools, jQuery, or&nbsp;Dojo</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[<a
href="http://davidwalsh.name/dw-content/twitter-follow.php"><img
src="http://davidwalsh.name/dw-content/twitter-button.jpg" alt="Twitter Button" class="image" /></a><p>There&#8217;s nothing like a subtle, slick website widget that effectively uses CSS and JavaScript to enhance the user experience.  Of course widgets like that take many hours to perfect, but it doesn&#8217;t take long for that effort to be rewarded with above-average user retention and buzz.  One of the widgets I love is Twitter&#8217;s &#8220;Follow&#8221; button.  Let me show you how you can implement this functionality with three popular JavaScript toolkits:  MooTools, jQuery, and Dojo.</p><p><em>Note:  This tutorial will only display the client side handling of the form submission &#8212; NOT any PHP/MySQL/server-side handling of the request.</em></p><div
class="actions"> <a
href="http://davidwalsh.name/dw-content/twitter-follow.php" class="demo">View MooTools Demo</a> <a
href="http://davidwalsh.name/dw-content/twitter-follow.php?lib=dojo" class="demo">View Dojo Demo</a> <a
href="http://davidwalsh.name/dw-content/twitter-follow.php?lib=jquery" class="demo">View jQuery Demo</a><div
class="clear"></div></div><h2>The HTML&nbsp;Structure</h2><pre class="html">
&lt;form class="follow-form" method="post" action="twitter-follow.php"&gt;
	&lt;input type="hidden" name="followID" value="123456" /&gt;
	&lt;button type="submit" value="Actions" class="btn follow" title="123456"&gt;
		&lt;i&gt;&lt;/i&gt;&lt;span&gt;follow&lt;/span&gt;
	&lt;/button&gt;
&lt;/form&gt;
</pre><p>The HTML for the button is very simple.  The structure revolves around a BUTTON element which contains an I element and SPAN element.  You&#8217;re probably thinking &#8220;An I element?  WTF.&#8221;  I know I did.  The truth of the matter is that the I element is deprecated and, as far as I&#8217;m concerned, and be used for any purpose the developer would like.  I&#8217;m also sure that Twitter doesn&#8217;t mind saving bytes here or there.</p><h2>The CSS&nbsp;Styles</h2><pre class="css">
/* twitter button and its children */
button.btn { 
	-moz-border-radius:4px;
	-webkit-border-radius:4px;
	background-attachment:scroll;
	background-color:#ddd;
	background-image:url(http://s.twimg.com/a/1282150308/images/buttons/bg-btn.gif);
	background-position:0 0;
	background-repeat:repeat-x;
	border:1px solid #ddd;
	border-bottom:1px solid #ccc;
	color:#333;
	cursor:pointer;
	font-family:"Lucida Grande",sans-serif;
	font-size:11px;
	line-height:14px;
	padding:4px 8px 5px 8px;
	text-shadow:1px 1px 0 #fff;
	vertical-align:top;
}
button.btn:hover {
	border:1px solid #999;
	border-bottom-color:#888;
	color:#000;
	background-color:#d5d5d5;
	background-position:0 -6px;
}
button.btn:active {
	background-image:none !important;
	text-shadow:none !important;
}
			
button.btn i {
	background-image:url(http://s.twimg.com/a/1282150308/images/sprite-icons.png);
	background-position:-176px -32px;
	background-repeat:no-repeat;
	display:inline-block;
	height:13px;
	margin-right:5px;
	width:15px;
}
button.btn i.active	{ background:url(http://s.twimg.com/a/1282150308/images/spinner.gif); }

/* properties for the element that is generated *after* following */
span.following	{  background:#ffd; padding:5px 10px; }
span.following span { width:10px; height:9px; margin-right:5px; display:inline-block; background:url("http://s.twimg.com/a/1282150308/images/sprite-icons.png") -160px -16px no-repeat; }
</pre><p>Most of the styling for this button goes onto the BUTTON element itself.  You&#8217;ll notice directives to round the button;  leaving the button sharp also please the eye.  Through the regular, hover, and active button states, check out how Twitter users the background position and colors to nicely modify the button without the need for additional images.  You&#8217;ll also notice Twitter uses sprites&#8230;as should you.</p><h2>The MooTools&nbsp;JavaScript</h2><pre class="js">
/* with mootools */
window.addEvent('domready',function() {
	/* fetch elements */
	$$('form.follow-form').each(function(form) {
		/* stop form event */
		form.addEvent('submit',function(e) {
			/* stop event */
			if(e) e.stop();
			/* send ajax request */
			var i = form.getElement('i');
			new Request({
				url: 'twitter-follow.php',
				method: 'post',
				data: {
					followID: form.getElement('input').value
				},
				onRequest: function() {
					i.addClass('active');
				},
				onSuccess: function() {
					var button = form.getElement('button');
					button.setStyle('display','none');
					new Element('span',{
						html: '&lt;span&gt;&lt;/span&gt;Following!',
						'class': 'following'
					}).inject(button,'after');
				},
				onComplete: function() {
					i.removeClass('active');
				}
			}).send();
		});
	});
});
</pre><p>The first step is grabbing all of the FORM elements with the follow-form CSS class.  Upon form submission, the default submission action is stopped.  An AJAX request is fired, using the INPUT element&#8217;s ID as the user to follow.  When the request is fired, the I element&#8217;s background image is set to the spinner.  When the request is complete, the button is hidden and a new SPAN element is displayed informing the user that they are now following the given user!</p><h2>The jQuery&nbsp;JavaScript</h2><pre class="js">
// Idiomatic jQuery by Doug Neiner
jQuery(function ($) {
	/* fetch elements and stop form event */
	$("form.follow-form").submit(function (e) {
		/* stop event */
		e.preventDefault();
		/* "on request" */
		$(this).find('i').addClass('active');
		/* send ajax request */
		$.post('twitter-follow.php', {
			followID: $(this).find('input').val()
		}, function () {
			/* find and hide button, create element */
			$(e.currentTarget)
			  .find('button').hide()
			  .after('&amp;lt;span class="following"&amp;gt;&amp;lt;span&amp;gt;&amp;lt;/span&amp;gt;Following!&amp;lt;/span&amp;gt;');
		});
	});
});
</pre><p>The code above is based off of the MooTools code.  The workflow is exactly the same.</p><h2>The Dojo&nbsp;JavaScript</h2><pre class="js">
/* when the DOM is ready */
dojo.ready(function() {
	/* fetch elements */
	dojo.query('form.follow-form').forEach(function(form) {
		/* stop form event */
		dojo.connect(form,'onsubmit',function(e) {
			/* stop event */
			dojo.stopEvent(e);
			/* active class */
			dojo.query('i',form).addClass('active');
			/* get button */
			var button = dojo.query('button',form)[0];
			/* ajax request */
			dojo.xhrPost({
				form: form,
				load: function() {
					dojo.style(button,'display','none');
					dojo.create('span',{
						innerHTML: '&lt;span&gt;&lt;/span&gt;Following',
						className: 'following'
					},button,'after');
				}
			});
		});
	});
});
</pre><p>The code above is based off of the MooTools code.  The workflow is exactly the same.</p><div
class="actions"> <a
href="http://davidwalsh.name/dw-content/twitter-follow.php" class="demo">View MooTools Demo</a> <a
href="http://davidwalsh.name/dw-content/twitter-follow.php?lib=dojo" class="demo">View Dojo Demo</a> <a
href="http://davidwalsh.name/dw-content/twitter-follow.php?lib=jquery" class="demo">View jQuery Demo</a><div
class="clear"></div></div><p>This &#8220;Follow&#8221; button is only one of many details that Twitter has paid attention to, just to make the user experience on the site better.  Take note from the effort put forth by large websites &#8212; adding these types of details to your smaller websites can make the user experience much better for YOUR users!</p><p><a
href="http://davidwalsh.name/twitter-button">Create a Twitter AJAX Button with MooTools, jQuery, or&nbsp;Dojo</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/twitter-button/feed</wfw:commentRss> <slash:comments>19</slash:comments> </item> <item><title>Accomplishing Common Tasks Using MooTools, jQuery, and Dojo&#160;III</title><link>http://davidwalsh.name/dojo-mootools-jquery</link> <comments>http://davidwalsh.name/dojo-mootools-jquery#comments</comments> <pubDate>Thu, 19 Aug 2010 02:32:54 +0000</pubDate> <dc:creator>David Walsh</dc:creator> <category><![CDATA[Dojo]]></category> <category><![CDATA[jQuery]]></category> <category><![CDATA[MooTools]]></category><guid
isPermaLink="false">http://davidwalsh.name/?p=5045</guid> <description><![CDATA[My love of the JavaScript frameworks knows no bounds. Unfortunately too many developers stick to one framework without taking the time to learn the others. The more frameworks you know, the better a programmer you will be and the more money you&#8217;ll make. Let me show you how to accomplish a few more tasks using [...]<p><a
href="http://davidwalsh.name/dojo-mootools-jquery">Accomplishing Common Tasks Using MooTools, jQuery, and Dojo&nbsp;III</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>My love of the JavaScript frameworks knows no bounds.  Unfortunately too many developers stick to one framework without taking the time to learn the others.  The more frameworks you know, the better a programmer you will be and the more money you&#8217;ll make.  Let me show you how to accomplish a few more tasks using three JavaScript frameworks:  MooTools, jQuery, and Dojo.</p><h2>Calculate Element Dimensions and&nbsp;Position</h2><p>Knowing not only the height and width of a dimension but it&#8217;s top/left position from an offset parent or document body can be extremely helpful when trying to animate or move a DOM element.</p><h3>MooTools</h3><pre class="js">
var dimensions = document.id('myElement').getDimensions();
/* returns:
{ 
	height: 4684,
	width: 1408,
	x: 1408,
	y: 4684
}
*/
</pre><h3>jQuery</h3><pre class="js">
var myElement = jQuery('#myElement');
var position = myElement.position();
var dimensions = {
	height: myElement.height(),
	width: myElement.width(),
	top: position.top,
	left: position.left
};
</pre><h3>Dojo</h3><pre class="js">
var dimension = dojo.coords('myElement');
/* returns:
{
	h: 4684,
	l: 0,
	t: 0,
	w: 1408,
	x: 0,
	y: 0
}
*/
</pre><h2>Extend an&nbsp;Object</h2><p>Extending an object means taking on object and merging a second objects properties into it.  This is very helpful in merging default options with instance options.</p><h3>MooTools</h3><pre class="js">
$extend(firstObject,{ anotherProperty:'anothervalue' });
//second arg is added to the first object
</pre><h3>jQuery</h3><pre class="js">
jQuery.extend(firstObject,{ anotherProperty:'anothervalue' })
</pre><h3>Dojo</h3><pre class="js">
dojo.mixin(firstObject,{ anotherProperty:'anothervalue' });
</pre><h2>Stop an&nbsp;Event</h2><p>Stopping an event is helpful when looking to execute functionality (usually an XHR request) when a link is clicked.</p><h3>MooTools</h3><pre class="js">
$('myElement').addEvent('click',function(e) {
	e.stop();
});
</pre><h3>jQuery</h3><pre class="js">
$('#myElement').click(function(e){ 
	event.stopPropagation();
	e.preventDefault();
	// (no internal method that does both)
});
</pre><h3>Dojo</h3><pre class="js">
dojo.connect(dojo.byId('myElement'),'onclick',function(e) {
	dojo.stopEvent(e);
});
</pre><h2>Load Content into an&nbsp;Element</h2><p>Sure we can create an XHR request manually to load content into an element but why do that when your favorite lirbary can do that work for you?</p><h3>MooTools</h3><pre class="js">
document.id('myElement').load('ajax/script.html');
</pre><h3>jQuery</h3><pre class="js">
jQuery('#myElement').load('ajax/script.html');
</pre><h3>Dojo</h3><pre class="js">
//as found on Pete Higgins' website:
//http://higginsforpresident.net/2009/12/140-characters-of-awesome/
dojo.extend(dojo.NodeList, {
	grab: function(url){
		dojo.xhr('GET', { url:url })
			.addCallback(this, function(response){
				this.addContent(response, 'only');
			});
		return this;
	}
});
dojo.query('#myElement').grab('header.html');
</pre><h2>Get and Set HTML&nbsp;Content</h2><p>Getting and setting HTML is a frequent JavaScript operation&#8230;yet each library handles it a bit differently.</p><h3>MooTools</h3><pre class="js">
//get
var html = document.id('myElement').get('html');
//set
document.id('myElement').set('html','<b>Hello!</b>');
</pre><h3>jQuery</h3><pre class="js">
//get
var html = jQuery('#myElement').html();
//set
jQuery('#myElement').html('<b>Hello!</b>');
</pre><h3>Dojo</h3><pre class="js">
//get 
var html = dojo.byId('myElement').innerHTML
//set
dojo.byId('myElement').innerHTML = '<b>Hello!</b>';
</pre><h2>Use Element&nbsp;Storage</h2><p>Element data storage is important because it allows you to store settings within the element itself &#8212; perfect for defeating scope and context issues.</p><h3>MooTools</h3><pre class="js">
//set
document.id('myElement').store('key','value');
//get
var value = document.id('myElement').retrieve('key');
</pre><h3>jQuery</h3><pre class="js">
//set
jQuery('#myElement').data('key','value');
//get
var value = jQuery('#myElement').data('key');
</pre><h3>Dojo</h3><pre class="js">
//set
dojo.attr('myElement','data-key','value');
//get
dojo.attr('myElement','data-key');
</pre><p>There you are &#8212; more proof that the toolkits are one in the same, all except the syntax.  Do yourself a favor and learn more than one JavaScript framework &#8212; you&#8217;ll be better for it!</p><p><a
href="http://davidwalsh.name/dojo-mootools-jquery">Accomplishing Common Tasks Using MooTools, jQuery, and Dojo&nbsp;III</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/dojo-mootools-jquery/feed</wfw:commentRss> <slash:comments>14</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/66 queries in 0.036 seconds using disk: basic
Object Caching 1469/1580 objects using disk: basic

Served from: davidwalsh.name @ 2012-05-23 22:53:25 -->
