<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Nettuts+ &#187; JavaScript &amp; AJAX</title>
	<atom:link href="http://net.tutsplus.com/category/tutorials/javascript-ajax/feed/" rel="self" type="application/rss+xml" />
	<link>http://net.tutsplus.com</link>
	<description>Web Development &#38; Design Tutorials</description>
	<lastBuildDate>Fri, 20 Nov 2009 19:56:34 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.8.4</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Sorting Values with JavaScript</title>
		<link>http://net.tutsplus.com/tutorials/javascript-ajax/sorting-values-with-javascript/</link>
		<comments>http://net.tutsplus.com/tutorials/javascript-ajax/sorting-values-with-javascript/#comments</comments>
		<pubDate>Thu, 19 Nov 2009 19:29:06 +0000</pubDate>
		<dc:creator>Andrew Burgess</dc:creator>
				<category><![CDATA[JavaScript & AJAX]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[jQuery]]></category>
		<category><![CDATA[sort]]></category>
		<category><![CDATA[sorting]]></category>

		<guid isPermaLink="false">http://net.tutsplus.com/?p=7837</guid>
		<description><![CDATA[<img src="http://nettuts.s3.amazonaws.com/498_js/200.jpg" />]]></description>
			<content:encoded><![CDATA[<p>Lists and tables are often the best way to display data on the web; but you shouldn&#8217;t have to worry about sorting that information manually. In today&#8217;s tutorial, you&#8217;re going to make a jQuery plugin that will put all your ducks in a row with JavaScript ease!</p>
<p><span id="more-7837"></span></p>
<div class="tutorial_image">
<a href="http://nettuts.s3.amazonaws.com/498_js/demo.zip"><img src="http://nettuts.com/wp-content/themes/nettuts/site_images/button_src_nm.jpg"></a><br />
<a href="http://nettuts.s3.amazonaws.com/498_js/demo/sort.htm"><img src="http://nettuts.com/wp-content/themes/nettuts/site_images/button_demo_nm.jpg"></a>
</div>
<h2>Preface</h2>
<p>So, how exactly does sorting work in JavaScript? It&#8217;s not too complicated: any array object has a sort method. If you don&#8217;t pass it any parameters, it will convert the objects in the array to strings, sort them pseudo-alphabetically, and return them. Usually, this is terrible; consider sorting the numbers 0 &#8211; 10 alphabetically. You would get this: [0, 1, 10, 2, 3, 4, 5, 6, 7, 8, 9]. Fortunately, we can pass a function to the sort method. That function should take two parameters (the two items to be compared): then, it will return 0 if they are equal, a negative number if the first parameter takes precedence, or a positive number of the second parameter should come first. So numbers are actually the simplest thing to sort &#8220;manually&#8221;: </p>
<pre class="js" name="code">
numberArray.sort(function(a, b) {
    return a - b
});
</pre>
<p>Obviously, this will return 0 if the numbers are equal, a negative number if <code>a</code> should be first, and a positive number if <code>b</code> should be first. </p>
<p>We&#8217;re going to look at sorting several different types of data, a few in multiple formats; but this will all be much more useful if we wrap it in a jQuery plugin, so let&#8217;s start by setting up that shell!</p>
<h2>The Plugin Shell</h2>
<div class="tutorial_image"><img alt="You still can't crate a jQuery Plugin" src="http://nettuts.s3.amazonaws.com/498_js/plugin.png" /></div>
<p>If you&#8217;re not familiar with writing jQuery plugins, check out Jeffrey Way&#8217;s Screencast &#8220;<a href="http://net.tutsplus.com/videos/screencasts/you-still-cant-create-a-jquery-plugin/">You still can&#8217;t create a jQuery Plugin?</a>&#8221; It&#8217;ll get you up to speed in no time if you&#8217;re comfortable with jQuery! (true confession: I&#8217;d actually never written a plugin until I made this one). </p>
<p>We&#8217;ll set up our plugin, called datasort, this way: we&#8217;ll pass it an array of items to sort; we can specify four parameters.</p>
<ul>
<li>datatype (the type of data you&#8217;re sorting)</li>
<li>sortElement (the child element you want to sort by, if desired)</li>
<li>sortAttr (the attribute you want to sort by, if desired)</li>
<li>reverse (the direction they should sort in)</li>
</ul>
<p>So a fully-modified call to our plugin might look like this:</p>
<pre class="js" name="code">
$('ul.names li).datasort({
    		datatype    : 'alpha',
    		sortElement : 'span.first',
    		sortAttr    : 'rel',
    		reverse     : true
    	});
</pre>
<p>Here&#8217;s the plugin shell:</p>
<pre class="js" name="code">
(function ($) {
  $.fn.datasort = function(options) {
    var defaults = {
    	//set the default parameter values
          datatype    : 'alpha',
          sortElement : false,
          sortAttr    : false,
          reverse     : false
          },
    // combine the default and user's parameters, overriding defaults
        settings = $.extend({}, defaults, options),
        datatypes = {},
        base = {},
        that = this;

    if (typeof settings.datatype === 'string') {
      that.sort(datatypes[settings.datatype]);
    }
    if (typeof settings.datatype === 'function') {
      that.sort(settings.datatype);
    }
    if(settings.reverse) {
      that = $($.makeArray(this).reverse());
    }
    $.each(that, function(index, element) { that.parent().append(element); });
  };
})(jQuery);
</pre>
<p>So here&#8217;s how it&#8217;ll work: we&#8217;ll set up all the variables at the beginning. Then, if the datatype parameter is a string, we&#8217;ll find the corresponding sort function in the datatypes object and sort with it; if the datatype parameter is a function, we&#8217;ll sort with it. Finally, if the reverse setting is set to true, we&#8217;ll reverse the order of the sorted items (since jQuery objects aren&#8217;t true JavaScript arrays, the reverse function won&#8217;t work on them; so we can use $.makeArray() to turn it into one; then, once it&#8217;s reversed, we re-jquery-fy it!).</p>
<h2>Laying a Bit More Groundwork</h2>
<p>At the very lowest level, you can sort almost any type of data in one of two ways: we&#8217;ll be calling them alphabetically and numerically. Let&#8217;s create these two functions as properties of your base object.</p>
<pre class="js" name="code">
base = {
  alpha : function(a, b) {
    a = a.toUpperCase();
    b = b.toUpperCase();
    return (a < b) ? -1 : (a > b) : 1 : 0;
    //ternary operator: condition ? returnIfTrue : returnIfFalse
  },
  number : function(a, b) {
    a = parseFloat(a);
    b = parseFloat(b);
    return a - b;
  }
},
</pre>
<p>Pretty simple, eh? Simply normalize the two values, compare and return. The tricky part is parsing the data that we want to send to these functions; that&#8217;s what we&#8217;ll do now. However, there&#8217;s one more thing.</p>
<p>When sorting items in the array, we might not want to sort simply by the text of the element itself. The sortElement and sortAttr parameters of our plugin are to this end. For example, we will likely want to sort table rows based on a certain column of table cells. In that case, we&#8217;d use $(&#8217;table tr&#8217;).datasort({ sortElement : &#8216;td.price&#8217; }). Or perhaps we want to sort a list of images by their alt attributes: $(&#8217;ul li&#8217;).datasort({sortElement : &#8216;img&#8217;, sortAttr : &#8216;alt&#8217;}). Because of all this, we need to add one more function to our base object:</p>
<pre class="js" name="code">
base = {
  alpha : function (a, b) { ... },
  number : function (a, b) { ... },
  extract : function (a, b) {
  	var get = function (i) {
      var o = $(i);
      if (settings.sortElement) {
        o = o.children(settings.sortElement);
      }
      if (settings.sortAttr) {
        o = o.attr(settings.sortAttr);
      } else {
        o = o.text();
      }
      return o;
    };
    return {
      a : get(a),
      b : get(b)
    };
  }
},
</pre>
<p>It may look complicated, but it&#8217;s not. We just create a jQuery object with each item; if sortElement is set, we use the children() method to get the right elements. Then, if a sortAttr is set, we get its value; if not, we get the element&#8217;s text. We&#8217;ve set all this to an inner function, and return an object with two properites; these properties are the values we must parse and send to the appropriate base sorting function.</p>
<p>This probably seemed like a lot of prep work, but what we were really doing is abstracting as much code as possible. This way, they&#8217;ll be much less repeat code, because the important actions have been bundled away as functions.</p>
<h2>Sorting Words and Numbers</h2>
<p>We&#8217;re finally here: the fun part! We&#8217;ll start by building two simple functions for our datatypes object. These will simple pass values to base.extract() and then pass those return values to the appropriate sorting class.</p>
<pre class="js" name="code">
datatypes = {
  alpha : function (a, b) {
    var o = base.extract(a, b);
    return base.alpha(o.a, o.b);
  },
  number : function(a, b) {
    var o = base.extract(a, b);
    for (var e in o) {
      o[e] = o[e].replace(/[$]?(-?\d+.?\d+)/, '\$1');
    }
    return base.number(o.a, o.b);
  },
},
</pre>
<p>Our alphabetic sorter should be obvious. The number sorter does a bit more: before passing the extracted values on, it strips out a dollar sign at the front. I&#8217;ve kept this regular expression simple, but you could parse a lot of different number formats here if you wanted to get complex. Let&#8217;s give our evolving plugin a try; create a basic html page:</p>
<pre class="html" name="code">
&lt;!DOCTYPE html>
&lt;html>
&lt;head>
  &lt;meta charset='utf-8' />
  &lt;title>Data Sorting&lt;/title>
  &lt;style type='text/css'>
  ul, table {
    display:table;
    float:left;
    background:#ececec;
    margin:10px;
    padding:0;
    border:1px solid #ccc;
  }
  li, tr {
    margin:0;
    padding:8px;
    border-top:1px solid #fff;
    border-bottom:1px solid #ccc;
    list-style-type:none;
  }
  li:first-child { border-top:0 }
  li:last-child { border-bottom:0 }
  &lt;/style>
&lt;/head>
&lt;body>
  &lt;table class='a'>
    &lt;thead>
      &lt;tr>
        &lt;th rel='alpha' class='first'>First Name&lt;/th>
        &lt;th rel='alpha' class='last'>Last Name&lt;/th>
      &lt;/tr>
    &lt;/thead>
    &lt;tbody>
      &lt;tr>&lt;td class="first">Jeffrey&lt;/td> &lt;td class="last">Way&lt;/td>&lt;/tr>
      &lt;tr>&lt;td class="first">Sean&lt;/td> &lt;td class="last">Hodge&lt;/td>&lt;/tr>
      &lt;tr>&lt;td class="first">Adam&lt;/td> &lt;td class="last">Miller&lt;/td>&lt;/tr>
      &lt;tr>&lt;td class="first">Ian&lt;/td> &lt;td class="last">Yates&lt;/td>&lt;/tr>
      &lt;tr>&lt;td class="first">Adrian&lt;/td> &lt;td class="last">Try&lt;/td>&lt;/tr>
      &lt;tr>&lt;td class="first">Caleb&lt;/td> &lt;td class="last">Aylsworth&lt;/td>&lt;/tr>
    &lt;/tbody>
  &lt;/table>

  &lt;ul class='n'>
  &lt;li>4.09&lt;/li>
  &lt;li>4.10&lt;/li>
  &lt;li>67.8&lt;/li>
  &lt;li>100&lt;/li>
  &lt;li>-98&lt;/li>
  &lt;li>67.7&lt;/li>
  &lt;li>23&lt;/li>
  &lt;/ul> 

  &lt;ul class="curr">
    &lt;li>$299.66&lt;/li>
    &lt;li>$299.57&lt;/li>
    &lt;li>$0.14&lt;/li>
    &lt;li>$80.00&lt;/li>
  &lt;/ul>

  &lt;script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js" />&lt;/script>
  &lt;script src="jquery.datasort.js" />&lt;/script>
  &lt;script type="text/javascript">
    $('table.a tbody tr').datasort({sortElement : 'td.last'});
    $('ul.n li').datasort({datatype: 'number', reverse: true});
    $('ul.curr li').datasort({ datatype: 'number' });
  &lt;/script>
&lt;/body>
&lt;/html>
</pre>
<p>I&#8217;ve included a table and two lists (and I&#8217;ve styled them briefly). Take note of our plugin calls: we&#8217;re using the default datatype for the table, but sorting by the table cells with a class of last; try changing this to &#8216;td.first.&#8217; Then, we sort the lists numerically, and reverse one of them. Here&#8217;s the proof of our labours:</p>
<div class="tutorial_image"><img src="http://nettuts.s3.amazonaws.com/498_js/alphaNumber.png" alt="Sorting Alphabetically and Numerically" /></div>
<p>Pretty nice, but those were relatively simple values; what if we want to be able to sort multiple formats for one type?</p>
<h2>Sorting Dates</h2>
<p>There are a number of different ways to write dates, which makes it pretty tricky to parse them for sorting. However, we can cover most of them with this:</p>
<pre class='js' name='code'>
date : function(a, b) {
  var o = base.extract(a, b);
  for (var e in o) {
  o[e] = o[e].replace(/-/g, '')
             .replace(/january|jan/i, '01')
             .replace(/february|feb/i, '02')
             .replace(/march|mar/i, '03')
             .replace(/april|apr/i, '04')
             .replace(/may/i, '05')
             .replace(/june|jun/i, '06')
             .replace(/july|jul/i, '07')
             .replace(/august|aug/i, '08')
             .replace(/september|sept|sep/i, '09')
             .replace(/october|oct/i, '10')
             .replace(/november|nov/i, '11')
             .replace(/december|dec/i, '12')
             .replace(/(\d{2}) (\d{2}), (\d{4})/, '\$3\$1\$2')
             .replace(/(\d{2})\/(\d{2})\/(\d{4})/, '\$3\$2\$1');
  }
  return base.number(o.a, o.b);
},
</pre>
<p>So what are we doing here? First, here&#8217;s the logic: if all the dates are formatted YYYYMMDD, they will sort correctly with numerical sorting. Our parser can sort the following date formats:</p>
<ul>
<li>YYYY-MM-DD</li>
<li>YYYYMMDD</li>
<li>DD/MM/YYYY</li>
<li>month DD, YYYY</li>
</ul>
<p>First we strip our dashes, which will leave YYYY-MM-DD ready for parsing. Then, we replace every month name or abbreviation with its number value. Finally, we have to rearrange the numbers for DD/MM/YYY and month DD, YYYY. That&#8217;s what the last two expressions do. To give this a try, paste this list into our HTML:</p>
<pre class="html" name="code">
&lt;ul class='date'>
  &lt;li>2009-10-06&lt;/li>
  &lt;li>sept 25, 1995&lt;/li>
  &lt;li>1990-06-18&lt;/li>
  &lt;li>20100131&lt;/li>
  &lt;li>June 18, 2009&lt;/li>
  &lt;li>02/11/1993&lt;/li>
  &lt;li>15941219&lt;/li>
  &lt;li>1965-08-05&lt;/li>
  &lt;li>1425-12-25&lt;/li>
&lt;/ul>
</pre>
<p>And call it with this:</p>
<pre class="js" name="code">
    $('ul.date li').datasort({datatype: 'date'});
</pre>
<div class="tutorial_image"><img src="http://nettuts.s3.amazonaws.com/498_js/date.png" alt="Sorting Dates" /></div>
<p>Is this a perfect date parser? Not by any means; we can&#8217;t sort DD/MM/YY, because there&#8217;s no way to know what century this is in. Also, we can&#8217;t tell the difference between DD/MM/YY and MM/DD/YY, so we just have to choose one. </p>
<h2>Sorting Time</h2>
<p>Sorting time values must be one of the most difficult values to sort: we need to be able to accept 12-hour time, 24-hour time, and values with or without AM/PM tags and seconds. I think it&#8217;s easiest to sort time alphabetically, even though its all numbers. Why? Consider these two timestamps: 00:15:37 and 12:15. The first one should come first, but if we sort them by number they&#8217;ll be parsed as floats, and end up like 1537 and 1215. Now, the second value will come first. Also, when sorting alphabetically, we don&#8217;t have to take out the colons (parseFloat() would choke on them). So here&#8217;s how it&#8217;s done.</p>
<pre class="js" name="code">
time : function(a, b) {
  var o = base.extract(a, b),
      afternoon = /^(.+) PM$/i;
  for (var e in o) {
    o[e] = o[e].split(':');
    var last = o[e].length - 1;

    if(afternoon.test(o[e][last])) {
      o[e][0] = (parseInt(o[e][0]) + 12).toString();
      o[e][last] = o[e][last].replace(afternoon, '\$1');
    }
    if(parseInt(o[e][0]) < 10 &#038;&#038; o[e][0].length === 1) {
      o[e][0] = '0' + o[e][0];
    }
    o[e][last] = o[e][last].replace(/^(.+) AM$/i, '\$1');

    o[e] = o[e].join('');
  }
  return base.alpha(o.a, o.b);
}
</pre>
<p>Let's go through this line by line. </p>
<pre class="js" name="code">
  var o = base.extract(a, b),
      afternoon = /^(.+) PM$/i;
</pre>
<p>We start with our variables: our extracted values and a regular expression to check for PM label. </p>
<pre class="js" name="code">
  for (var e in o) {
    o[e] = o[e].split(':');
    var last = o[e].length - 1;

    if(afternoon.test(o[e][last])) {
      o[e][0] = (parseInt(o[e][0]) + 12).toString();
      o[e][last] = o[e][last].replace(afternoon, '\$1');
    }
</pre>
<p>Next, we'll start a for loop, going through each of the values we're sorting; first, we split it into an array at the colons. We create an easy way to get to the last items of the array: our 'last' variable. Then, we test our PM regex on the last item in our array; if it returns true, this value has the PM tag. Therefore, we'll add 12 to the first item in our array, which will be the hour value; we do this because we need all the values to be formatted in  24-hour time. (Note that to do this, we must convert it to a number, add 12, and then turn it back into a string). Finally, we use the PM regex again to remove that label from the last item in the array.</p>
<pre class="js" name="code">
    if(parseInt(o[e][0]) < 10 &#038;&#038; o[e][0].length === 1) {
      o[e][0] = '0' + o[e][0];
    }
   o[e][last] = o[e][last].replace(/^(.+) AM$/i, '\$1');

    o[e] = o[e].join('');
}
return base.alpha(o.a, o.b);
</pre>
<p>In this last chunk, we check the hour value for two conditions: is it less than 10? and does the string have only one character? This is important because a value like 08 will parse as 8 and be less than 10; but we're trying to see if we need to add a zero to the front. If the string has only one character, then we add the zero, so 3 becomes 03. This will keep things in order!</p>
<p>Before joining the array, we remove any AM labels. So now this . . .</p>
<pre class="html" name="code">
&lt;ul class='time'>
  &lt;li>1:15:47&lt;/li>
  &lt;li>3:45 PM&lt;/li>
  &lt;li>12:00:17&lt;/li>
  &lt;li>06:56&lt;/li>
  &lt;li>19:39&lt;/li>
  &lt;li>4:32 AM&lt;/li>
  &lt;li>00:15:36&lt;/li>
&lt;/ul>
</pre>
<p>. . . can be sorted with this . . . </p>
<pre class='js' name='code'>
$('ul.time li').datasort({datatype: 'time'});
</pre>
<p>And we're done! Behold the fruits of our labour:</p>
<div class="tutorial_image"><img src="http://nettuts.s3.amazonaws.com/498_js/time.png" alt="Sorting Time" /></div>
<h2>More Random Values</h2>
<p>We've set up our jQuery plugin so that users can pass sorting functions as the datatype parameter. This allows us to easily extend the plugin, although we don't have access to the base 'class' from the plugin call. We can easily write a function to sort psudeo-ratings:</p>
<pre class="js" name="code">
$('ul.rating li').datasort({datatype: function(a, b) {
      var o  = {
      a : $(a).text(),
      b : $(b).text()
      }
      for (var e in o) {
        o[e] = o[e].replace(/poor/i, 0)
                   .replace(/satisfactory/i, 1)
                   .replace(/good/i, 2)
                   .replace(/excellent/i, 3);
      }
      return o.a - o.b;
    }
});
</pre>
<p>This uses the simplest regular expressions possible to sort a list like this:</p>
<pre class="html" name="code">
&lt;ul class="rating">
  &lt;li>Good&lt;/li>
  &lt;li>Excellent&lt;/li>
  &lt;li>Poor&lt;/li>
  &lt;li>Satisfactory&lt;/li>
&lt;/ul>
</pre>
<h2>That's a Wrap!</h2>
<p>Now you're in the know: sorting values in JavaScript really isn't as hard as you might have thought. You can imagine this being useful to sort a table, with something like this:</p>
<pre class='js' name='code'>
$('table#myTable thead th').toggle(
  function() {
    var $this = $(this);
    $('table#myTable tbody tr').datasort({
      datatype: $this.attr('rel'),
      sortElement: 'td.' + $this.attr('class')
    });
  },
  function() {
    var $this = $(this);
    $('table#myTable tbody tr').datasort({
      datatype: $this.attr('rel'),
      sortElement: 'td.' + $this.attr('class'),
      reverse: true
      });
  }
);
</pre>
<p>(Try replacing the jQuery code for the table in the first example with this!)</p>
<p>Of course, we could improve this plugin a lot; for example, we could have it check the <code>rel</code> atttribute for a datatype if one isn't given as a parameter, and default to alpha if there is no <code>rel</code>. But that's aside from the sorting. </p>
<p>In sum, to sort with JavaScipt, we follow these steps:</p>
<ol>
<li>Determine the different formats you want to sort.</li>
<li>Decide what format you want to sort in.</li>
<li>Sort the array of items with the sort() method, passing in a function that will convert the two items to your desired format before comparing them</li>
</ol>
<p>Have a datatype to add to our plugin? Have a better way of sorting one of these? Let's hear it in the comments!</p>
<ul class="webroundup">
<li>Follow us on <a href="http://www.twitter.com/nettuts">Twitter</a>, or subscribe to the <a href="http://feeds.feedburner.com/nettuts" title="Nettuts+ RSS Feed">Nettuts+ RSS Feed</a> for the best web development tutorials on the web.</li>
</ul>
<p>
<script type="text/javascript"><!--digg_url = "post permalink (not digg url)"; // -->
</script><br />
<script src="http://digg.com/tools/diggthis.js" type="text/javascript"></script></p>
]]></content:encoded>
			<wfw:commentRss>http://net.tutsplus.com/tutorials/javascript-ajax/sorting-values-with-javascript/feed/</wfw:commentRss>
		<slash:comments>21</slash:comments>
		</item>
		<item>
		<title>The Basics of Object-Oriented JavaScript</title>
		<link>http://net.tutsplus.com/tutorials/javascript-ajax/the-basics-of-object-oriented-javascript/</link>
		<comments>http://net.tutsplus.com/tutorials/javascript-ajax/the-basics-of-object-oriented-javascript/#comments</comments>
		<pubDate>Wed, 11 Nov 2009 14:10:24 +0000</pubDate>
		<dc:creator>Leigh Kaszick</dc:creator>
				<category><![CDATA[JavaScript & AJAX]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[json]]></category>
		<category><![CDATA[objects]]></category>

		<guid isPermaLink="false">http://net.tutsplus.com/?p=7670</guid>
		<description><![CDATA[<img src="http://nettuts.s3.amazonaws.com/490_json/200x200.jpg" alt="The Basics of Object-Oriented JavaScript" />]]></description>
			<content:encoded><![CDATA[<p>Over recent years, JavaScript has increasingly gained popularity, partly due to libraries that are developed to make JavaScript apps/effects easier to create for those who may not have fully grasped the core language yet. </p>
<p>While in the past it was a common argument that JavaScript was a basic language and was very &#8217;slap dash&#8217; with no real foundation; this is no longer the case, especially with the introduction of high scale web applications and &#8216;adaptations&#8217; such as JSON (JavaScript Object Notation). </p>
<p><span id="more-7670"></span></p>
<p>JavaScript can have all that an Object-Orientated language has to offer, albeit with some extra effort outside of the scope of this article. </p>
<h3>Let&#8217;s Create an Object</h3>
<pre name="code" class="javascript">
    function myObject(){

    };
</pre>
<p>Congratulations, you just created an object. There are two ways to<br />
create a JavaScript object: they are &#8216;Constructor functions&#8217; and<br />
&#8216;Literal notation&#8217;. The one above is a Constructor function,<br />
I&#8217;ll explain what the difference is shortly, but before I do, here<br />
is what an Object definition looks like using literal notation.</p>
<pre name="code" class="javascript">
    var myObject = {

    };
</pre>
<p>Literal is a preferred option for name spacing so that your JavaScript<br />
code doesn&#8217;t interfere (or vice versa) with other scripts running on the<br />
page and also if you are using this object as a single object and not requiring<br />
more than one instance of the object, whereas Constructor function type<br />
notation is preferred if you need to do some initial work before the object<br />
is created or require multiple instances  of the object where each instance<br />
can be changed during the lifetime of the script. Let&#8217;s continue to build<br />
on both our objects simultaneously so we can observe what the differences are.</p>
<h3>Defining Methods and Properties</h3>
<h4>Constructor version:</h4>
<pre name="code" class="javascript">
    function myObject(){
        this.iAm = 'an object';
        this.whatAmI = function(){
            alert('I am ' + this.iAm);
        };
    };
</pre>
<h4>Literal version:</h4>
<pre name="code" class="javascript">
    var myObject = {
        iAm : 'an object',
        whatAmI : function(){
            alert('I am ' + this.iAm);
        }
    }
</pre>
<p>For each of the objects we have created a property &#8216;iAm&#8217; which contains a<br />
string value that is used in our objects method &#8216;whatAmI&#8217; which alerts a message. </p>
<blockquote>
<p>
Properties are variables created inside an object and methods are functions created inside an object.
</p>
</blockquote>
<p>Now is probably as good a time as any to explain how to use properties and<br />
methods (although you would already have done so if you are familiar with a library).</p>
<p>To use a property first you type what object it belongs to &#8211; so in this case it&#8217;s myObject &#8211;<br />
and then to reference its internal properties, you put a full stop and then the name of the<br />
property so it will eventually look like myObject.iAm (this will return &#8216;an object&#8217;).</p>
<p>For methods, it is the same except to execute the method, as with any function, you must<br />
put parenthesis after it; otherwise you will just be returning a reference to the function<br />
and not what the function actually returns. So it will look like myObject.whatAmI()<br />
(this will alert &#8216;I am an object&#8217;).</p>
<h4>Now for the differences:</h4>
<ul>
<li>The constructor object has its properties and methods defined with the<br />
    keyword &#8216;this&#8217; in front of it, whereas the literal version does not.</li>
<li>In the constructor object the properties/methods have their &#8216;values&#8217;<br />
    defined after an equal sign &#8216;=&#8217; whereas in the literal version, they are<br />
    defined after a colon &#8216;:&#8217;.</li>
<li>The constructor function can have (optional) semi-colons &#8216;;&#8217; at the<br />
    end of each property/method declaration whereas in the literal version<br />
    if you have more than one property or method, they MUST be separated with<br />
    a comma &#8216;,&#8217;, and they CANNOT have semi-colons after them, otherwise JavaScript will return an error.</li>
</ul>
<p>There is also a difference between the way these two types of object declarations are used.</p>
<p>To use a literally notated object, you simply use it by referencing its variable name,<br />
so wherever it is required you call it by typing;</p>
<pre name="code" class="javascript">
    myObject.whatAmI();
</pre>
<p>With constructor functions you need to instantiate (create a new instance of)<br />
the object first; you do this by typing;</p>
<pre name="code" class="javascript">
    var myNewObject = new myObject();
    myNewObject.whatAmI();
</pre>
<h3>Using a Constructor Function.</h3>
<p>Let&#8217;s use our previous constructor function and build upon it so it performs some basic<br />
(but dynamic) operations when we instantiate it.</p>
<pre name="code" class="javascript">
    function myObject(){
        this.iAm = 'an object';
        this.whatAmI = function(){
            alert('I am ' + this.iAm);
        };
    };
</pre>
<p>Just like any JavaScript function, we can use arguments with our constructor function;</p>
<pre name="code" class="javascript">
function myObject(what){
	this.iAm = what;
	this.whatAmI = function(language){
		alert('I am ' + this.iAm + ' of the ' + language + ' language');
	};
};
</pre>
<p>Now let&#8217;s instantiate our object and call its whatAmI method, filling in the required<br />
fields as we do so.</p>
<pre name="code" class="javascript">
    var myNewObject = new myObject('an object');
    myNewObject.whatAmI('JavaScript');
</pre>
<p>This will alert &#8216;I am an object of the JavaScript language.&#8217;</p>
<h3>To Instantiate or not to Instantiate</h3>
<p>I mentioned earlier about the differences between Object Constructors and Object Literals and that<br />
when a change is made to an Object Literal it affects that object across the entire script, whereas when<br />
a Constructor function is instantiated and then a change is made to that instance, it won&#8217;t affect any<br />
other instances of that object. Let&#8217;s try an example;</p>
<p>First we will create an Object literal;</p>
<pre name="code" class="javascript">
	var myObjectLiteral = {
    	myProperty : 'this is a property'
    }

    //alert current myProperty
    alert(myObjectLiteral.myProperty); //this will alert 'this is a property'

    //change myProperty
    myObjectLiteral.myProperty = 'this is a new property';

    //alert current myProperty
    alert(myObjectLiteral.myProperty); //this will alert 'this is a new property', as expected
</pre>
<p>Even if you create a new variable and point it towards the object, it will have the same effect.</p>
<pre name="code" class="javascript">
	var myObjectLiteral = {
    	myProperty : 'this is a property'
    }

    //alert current myProperty
    alert(myObjectLiteral.myProperty); //this will alert 'this is a property'

    //define new variable with object as value
    var sameObject = myObjectLiteral;

    //change myProperty
    myObjectLiteral.myProperty = 'this is a new property';

    //alert current myProperty
    alert(sameObject.myProperty); //this will still alert 'this is a new property'
</pre>
<p>Now let&#8217;s try a similar exercise with a Constructor function.</p>
<pre name="code" class="javascript">
	//this is one other way of creating a Constructor function
	var myObjectConstructor = function(){
    	this.myProperty = 'this is a property'
    }

    //instantiate our Constructor
    var constructorOne = new myObjectConstructor();

    //instantiate a second instance of our Constructor
    var constructorTwo = new myObjectConstructor();

    //alert current myProperty of constructorOne instance
    alert(constructorOne.myProperty); //this will alert 'this is a property'

     //alert current myProperty of constructorTwo instance
    alert(constructorTwo.myProperty); //this will alert 'this is a property'
</pre>
<p>So as expected, both return the correct value, but let&#8217;s change the myProperty for one of the instances.</p>
<pre name="code" class="javascript">
	//this is one other way of creating a Constructor function
	var myObjectConstructor = function(){
    	this.myProperty = 'this is a property'
    }

    //instantiate our Constructor
    var constructorOne = new myObjectConstructor();

    //change myProperty of the first instance
    constructorOne.myProperty = 'this is a new property';

    //instantiate a second instance of our Constructor
    var constructorTwo = new myObjectConstructor();

    //alert current myProperty of constructorOne instance
    alert(constructorOne.myProperty); //this will alert 'this is a new property'

     //alert current myProperty of constructorTwo instance
    alert(constructorTwo.myProperty); //this will still alert 'this is a property'
</pre>
<p>As you can see from this example, even though we changed the property of constructorOne<br />
it didn&#8217;t affect myObjectConstructor and therefore didn&#8217;t affect constructorTwo. Even if<br />
constructorTwo was instantiated before we changed the myProperty property of constructorOne,<br />
it would still not affect the myProperty property of constructorTwo as it is a completely different<br />
instance of the object within JavaScript&#8217;s memory.</p>
<p>So which one should you use? Well it depends on the situation, if you only need one object of its kind for<br />
your script (as you will see in our example at the end of this article), then use an object literal, but if you need several instances of an object, where each instance<br />
is independent of the other and can have different properties or methods depending on the way it&#8217;s constructed, then use a constructor function.</p>
<h3>This and That</h3>
<p>While explaining constructor functions, there were a lot of &#8216;this&#8217; keywords being thrown around<br />
and I figure what better time to talk about scope!</p>
<p>Now you might be asking &#8216;what is this scope you speak of&#8217;?&#8217; Scope in JavaScript is function/object based, so that means if you&#8217;re outside<br />
of a function, you can&#8217;t use a variable that is defined inside a function (unless you use a closure).</p>
<p>There is however a scope chain, which means that a function inside another function can access a<br />
variable defined in its parent function. Let&#8217;s take a look at some example code.</p>
<pre name="code" class="javascript">
&lt;script type="text/javascript"&gt;

var var1 = 'this is global and is available to everyone';

function function1(){

	var var2 = 'this is only available inside function1 and function2';	

	function function2(){

		var var3 = 'this is only available inside function2';

	}		

}

&lt;/script&gt;
</pre>
<p>As you can see in this example, <strong>var1</strong> is defined in the global object<br />
and is available to all functions and object, <strong>var2</strong> is defined inside function1<br />
and is available to function1 and function2, but if you try to reference it from the global object<br />
it will give you the error &#8216;var2 is undefined&#8217;, <strong>var3</strong> is only accessible to function2.</p>
<p>So what does &#8216;this&#8217; reference? Well in a browser, &#8216;this&#8217; references the window object, so technically<br />
the window is our global object. If we&#8217;re inside an object, &#8216;this&#8217; will refer to the object itself however<br />
if you&#8217;re inside a function, this will still refer to the window object and likewise if you&#8217;re inside a method<br />
that is within an object, &#8216;this&#8217; will refer to the object.</p>
<p>Due to our scope chain, if we&#8217;re inside a sub-object (an object inside an object), &#8216;this&#8217; will refer to<br />
the sub-object and not the parent object.</p>
<p>As a side note, it&#8217;s also worth adding that when using functions like setInterval, setTimeout and eval,<br />
when you execute a function or method via one of these, &#8216;this&#8217; refers to the window object as these are methods of window, so<br />
setInterval() and window.setInterval() are the same.</p>
<p>Ok now that we have that out of the way, let&#8217;s do a real world example and create a<br />
form validation object!</p>
<h3>Real world Usage: A Form Validation Object</h3>
<p>First I must introduce you to the addEvent function which we will create and is a<br />
combination of ECMAScript&#8217;s (Firefox, Safari, etc.. ) addEventListener() function and<br />
Microsoft ActiveX Script&#8217;s attachEvent() function.</p>
<pre name="code" class="javascript">
    function addEvent(to, type, fn){
        if(document.addEventListener){
            to.addEventListener(type, fn, false);
        } else if(document.attachEvent){
            to.attachEvent('on'+type, fn);
        } else {
            to['on'+type] = fn;
        }
    };
</pre>
<p>This creates a new function with three arguments, <strong>to</strong> being the DOM object we are attaching<br />
the event to, <strong>type</strong> being the type of event and <strong>fn</strong> being the function run when<br />
the event is triggered. It first checks whether addEventListener is supported, if so it will use that, if not it will check<br />
for attachEvent and if all else fails you are probably using IE5 or something equally obsolete so<br />
we will add the event directly onto its event property (note: the third option will overwrite any<br />
existing function that may have been attached to the event property while the first two will add<br />
it as an additional function to its event property).</p>
<p>Now let&#8217;s set up our document so it is similar to what you might see when you develop jQuery stuff.</p>
<p>In jQuery you would have;</p>
<pre name="code" class="javascript">
    $(document).ready(function(){
        //all our code that runs after the page is ready goes here
    });
</pre>
<p>Using our addEvent function we have;</p>
<pre name="code" class="javascript">
    addEvent(window, 'load', function(){
		//all our code that runs after the page is ready goes here
	});
</pre>
<p>Now for our Form object.</p>
<pre name="code" class="javascript">
var Form = {

	validClass : 'valid',

	fname : {
		minLength : 1,
		maxLength : 15,
		fieldName : 'First Name'
	},

	lname : {
		minLength : 1,
		maxLength : 25,
		fieldName : 'Last Name'
	},

	validateLength : function(formEl, type){
		if(formEl.value.length > type.maxLength || formEl.value.length < type.minLength ){
			formEl.className = formEl.className.replace(' '+Form.validClass, '');
			return false;
		} else {
			if(formEl.className.indexOf(' '+Form.validClass) == -1)
			formEl.className += ' '+Form.validClass;
			return true;
		}
	},

	validateEmail : function(formEl){
		var regEx = /^([0-9a-zA-Z]([-.\w]*[0-9a-zA-Z])*@([0-9a-zA-Z][-\w]*[0-9a-zA-Z]\.)+[a-zA-Z]{2,9})$/;
		var emailTest = regEx.test(formEl.value);
		if (emailTest) {
			if(formEl.className.indexOf(' '+Form.validClass) == -1)
			formEl.className += ' '+Form.validClass;
			return true;
		} else {
			formEl.className = formEl.className.replace(' '+Form.validClass, '');
			return false;
		}
	},		

	getSubmit : function(formID){
		var inputs = document.getElementById(formID).getElementsByTagName('input');
		for(var i = 0; i < inputs.length; i++){
			if(inputs[i].type == 'submit'){
				return inputs[i];
			}
		}
		return false;
	}			

};
</pre>
<p>So this is quite basic but can easily be expanded upon.</p>
<p>To break this down first we create a new property which is just the string name of our 'valid' css class<br />
that when applied to the form field, adds valid effects such as a green border. We also define our two sub-objects, <strong>fname</strong> and <strong>lname</strong>,<br />
so we can define their own properties that can be used by methods elsewhere, these properties are <strong>minLength</strong><br />
 which is the minimum amount of characters these fields can have, <strong>maxLength</strong> which is the max characters<br />
 the field can have and <strong>fieldName</strong> which doesn't actually get used, but could be grabbed for<br />
 things like identifying the field with a user friendly string in an error message (eg. 'First Name field is required.').</p>
<p>Next we create a validateLength method that accepts two arguments: <strong>formEl</strong> the DOM element to validate<br />
and the <strong>type</strong> which refers to one of the sub-object to use (i.e. fname or lname).<br />
This function checks whether the length of the field is between the minLength and maxLength range, if it's not<br />
then we remove our valid class (if it exists) from the element and return false, otherwise if it is then we add the valid class and return true.</p>
<p>Then we have a validateEmail method which accepts a DOM element as an arguement, we then test this DOM elements value against an<br />
email type regular expression; again if it passes we add our class and return true and vice versa.</p>
<p>Finally we have a getSubmit method. This method is given the id of the form and then loops through all input elements inside the specified form<br />
to find which one has a type of submit (type="submit"). The reason for this method is to return the submit button so we can<br />
disable it until the form is ready to submit.</p>
<p>Let's put this validator object to work on a real form. First we need our HTML.</p>
<pre name="code" class="javascript">
    &lt;body&gt;

    &lt;form id="ourForm"&gt;
        &lt;label&gt;First Name&lt;/label&gt;&lt;input type="text" /&gt;&lt;br /&gt;
        &lt;label&gt;Last Name&lt;/label&gt;&lt;input type="text" /&gt;&lt;br /&gt;
        &lt;label&gt;Email&lt;/label&gt;&lt;input type="text" /&gt;&lt;br /&gt;
        &lt;input type="submit" value="submit" /&gt;
    &lt;/form&gt;

    &lt;/body&gt;
</pre>
<p>Now let's access these input objects using JavaScript and validate them when the form submits.</p>
<pre name="code" class="javascript">
addEvent(window, 'load', function(){

	var ourForm = document.getElementById('ourForm');
	var submit_button = Form.getSubmit('ourForm');
	submit_button.disabled = 'disabled';

	function checkForm(){
		var inputs = ourForm.getElementsByTagName('input');
		if(Form.validateLength(inputs[0], Form.fname)){
			if(Form.validateLength(inputs[1], Form.lname)){
				if(Form.validateEmail(inputs[2])){ 					 

						submit_button.disabled = false;
						return true;

				}
			}
		}

		submit_button.disabled = 'disabled';
		return false;

	};

	checkForm();
	addEvent(ourForm, 'keyup', checkForm);
	addEvent(ourForm, 'submit', checkForm);

});
</pre>
<p>Let's break down this code.</p>
<p>We wrap our code in the addEvent function so when the window is loaded this script runs.<br />
Firstly we grab our form using its ID and put it in a variable named <strong>ourForm</strong>, then we grab<br />
our submit button (using our Form objects getSubmit method) and put it in a variable named <strong>submit_button</strong>,<br />
and then set the submit buttons disabled attribute to 'disabled'.</p>
<p>Next we define a checkForm function. This stores all the inputs inside the form field as an array and we attach it to a<br />
variable named.. you guessed it.. <strong>inputs</strong>!<br />
Then it defines some nested if statements which test each of the fields inside the inputs array against our Form methods.<br />
This is the reason we returned true or false in our methods, so if it returns true, we pass that if statement and continue onto the next,<br />
but if it returns false, we exit the if statements.</p>
<p>Following our function definition, we execute the checkForm function when the page initially loads and also attach the function to a keyup event<br />
and a submit event.</p>
<p>You might be asking, why attach to submit if we disabled the submit button. Well if you are focused on an input field and hit the enter key, it will<br />
attempt to submit the form and we need to test for this, hence the reason our checkForm function returns true (submits the form) or false (doesn't submit form).</p>
<h3>Conclusion</h3>
<p>So we learned how to define the different object types within JavaScript and create properties and methods within them. We also learned a nifty addEvent function and got to use our object in a basic real world example.</p>
<p>This concludes the basics of JavaScript Object Orientation. Hopefully, this may start you on your way to building your own JavaScript library! If you liked this article and are interested in other JavaScript related topics, post them in the comments as I'd be happy to continue writing them. Thanks for reading.</p>
<ul class="webroundup">
<li>Follow us on <a href="http://www.twitter.com/nettuts">Twitter</a>, or subscribe to the <a href="http://feeds.feedburner.com/nettuts" title="Nettuts+ RSS Feed">Nettuts+ RSS Feed</a> for the best web development tutorials on the web.</li>
</ul>
<p>
<script type="text/javascript"><!--digg_url = "post permalink (not digg url)"; // -->
</script><br />
<script src="http://digg.com/tools/diggthis.js" type="text/javascript"></script></p>
]]></content:encoded>
			<wfw:commentRss>http://net.tutsplus.com/tutorials/javascript-ajax/the-basics-of-object-oriented-javascript/feed/</wfw:commentRss>
		<slash:comments>41</slash:comments>
		</item>
		<item>
		<title>Build a Simple Password Strength Checker</title>
		<link>http://net.tutsplus.com/tutorials/javascript-ajax/build-a-simple-password-strength-checker/</link>
		<comments>http://net.tutsplus.com/tutorials/javascript-ajax/build-a-simple-password-strength-checker/#comments</comments>
		<pubDate>Wed, 04 Nov 2009 20:15:37 +0000</pubDate>
		<dc:creator>Siddharth</dc:creator>
				<category><![CDATA[JavaScript & AJAX]]></category>
		<category><![CDATA[password]]></category>
		<category><![CDATA[password checker]]></category>

		<guid isPermaLink="false">http://net.tutsplus.com/?p=7565</guid>
		<description><![CDATA[<img src="http://nettuts.s3.amazonaws.com/483_password/200x200.png" alt="Build a Simple Password Strength Checker" />]]></description>
			<content:encoded><![CDATA[<p>Providing instant feedback is the in-thing right now. Why limit yourself to checking usernames and email addresses? Why not extend this to provide quick visual feedback about the strength of the password the user has input? Today, we&#8217;ll take a look at how to create a simple password strength checker using the jQuery library, regular expressions and a simple algorithm.
</p>
<p><span id="more-7565"></span></p>
<div class="tutorial_image">
<a href="http://nettuts.s3.amazonaws.com/483_password/demo/demo.zip"><img src="http://nettuts.com/wp-content/themes/nettuts/site_images/button_src_nm.jpg"></a><br />
<a href="http://nettuts.s3.amazonaws.com/483_password/demo/code.html"><img src="http://nettuts.com/wp-content/themes/nettuts/site_images/button_demo_nm.jpg"></a>
</div>
<h3>A Word From the Author</h3>
<p>As most security experts will tell you, the user is always the weakest link. The most secure of systems are vulnerable when a user chooses an extremely ill-advised password. With that in mind, the recent trend seems to be providing quick feedback to the user regarding the strength of the password so the user can extend or modify the password to make it more secure.  </p>
<div class="tutorial_image">
   <img src="http://nettuts.s3.amazonaws.com/483_password/images/google.gif" alt="Hovers" />
</div>
<p>Today, we are going to use the jQuery library, a bunch of regular expressions and a very simple algorithm to create a basic password strength checker. Interested? Let&#8217;s get started right away! Here is a demo of what we are trying to build today:</p>
<div class="tutorial_image">
   <img src="http://nettuts.s3.amazonaws.com/483_password/images/demo.png" alt="Demo image" />
</div>
<h3>Design Goals</h3>
<p>Our design goals for this specific functionality is relatively small. </p>
<ul>
<li>Provide visual feedback to the user regarding the strength of their password.</li>
<li>The feedback has to be instantaneous. This means no clicking on a button to test the strength.</li>
<li>The trigger event can be any of the key board events. I&#8217;ve chosen keyup since this is the most appropriate for our specific need.</li>
<li>For the visual feedback, modifying the text alone, while useful, is severely lacking. I&#8217;ve chosen to change the background colors as well to draw the user&#8217;s attention to this.</li>
<li>Provide additional quantifiable feedback so the user knows in which departments the password lacks strength and how it can be improved.</li>
</ul>
<p>Now that we&#8217;ve adequately figured out our needs, we can move on to the next stage.</p>
<h3>Plan of Action</h3>
<p>We&#8217;ll now decide on the order of the individual steps that need to be done. </p>
<ul>
<li>Hook up the event handler to the <em>keyup</em> event of the input box.</li>
<li>Let the event handler check the input but delegate everything else to individual helper methods.</li>
<li>The helper methods should take care of parsing the input and analyzing it, computing the complexity and printing out the results.</li>
<li>Make sure the event handlers fires off the helper methods only if the length of the input is greater than the expected minimum so as to not waste CPU cycles on invalid entries.</li>
<li>Return control to the event handler in case anything else needs to be done. </li>
</ul>
<h3>The Algorithm</h3>
<div class="tutorial_image">
   <img src="http://nettuts.s3.amazonaws.com/483_password/images/algo.png" alt="The Algorithm" />
</div>
<p>In in the interest of keeping this write up succinct and approachable, I&#8217;ve decided to go with a very basic algorithm. The algorithm analyzes the string, gives bonuses for extra length, presence of numbers, symbols and upper case letters and penalties for letter or number only inputs. We aren&#8217;t going to look at matching common patterns or checking the input against a dictionary since this is out of the scope of the article. If interest peaks, I may do an article about this in the future.</p>
<p>First we check the length of the input string. If it&#8217;s greater than the minimum length, give it a base score of 50. Else make it 0. Next iterate through each character of the string and check if it is a symbol, number or upper case letter. If so, make a note of it. </p>
<p>Then check how many extra characters the string has, over the recommended minimum and grant a bonus for each character. Also grant a bonus if the string contains a combination of upper case letters, numbers and symbols or all three. Grant a bonus for each&#8217;s presence too.</p>
<p>Check if the string only contains either lower case letters or numbers and if so, penalize. </p>
<p>Add up all the numbers and decide the strength of the password accordingly.</p>
<p>That&#8217;s the long and short of the algorithm. It&#8217;s not going exceedingly suave but it catches a lot of bad passwords. You&#8217;ll understand this better once we see it in code.</p>
<h3>Core Markup</h3>
<p>The HTML markup of the demo page looks like so:</p>
<pre name="code" class="html">
&lt;!DOCTYPE html&gt;
&lt;html lang="en-GB"&gt;
&lt;head&gt;
&lt;title&gt;Simple Password Strength Checker - by Siddharth for NetTuts&lt;/title&gt;
&lt;link type="text/css" href="css/style.css" rel="stylesheet" /&gt;
&lt;script type="text/javascript" src="js/jquery.js"&gt;&lt;/script&gt;
&lt;script type="text/javascript" src="js/mocha.js"&gt;&lt;/script&gt;
&lt;/head&gt;
&lt;body&gt;

&lt;div id="container"&gt;

&lt;h1&gt;Create a simple password strength checker&lt;/h1&gt;

&lt;h2 class="bolded"&gt;by Siddharth for the lovely folks at Net Tuts&lt;/h2&gt;

&lt;p&gt;Type in your password to get visual feedback regarding the strength of your password.&lt;/p&gt;
&lt;p&gt;I assure you, I am not stealing your passwords. The form doesn't not submit. You can look through the source if you are suspicious. <img src='http://net.tutsplus.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> &lt;/p&gt; 

&lt;div class="block"&gt;
&lt;input id="inputPassword"/&gt;
&lt;div id="complexity" class="default"&gt;Enter a random value&lt;/div&gt;
&lt;/div&gt;

&lt;div class="block"&gt;
&lt;div id="results" class="default"&gt;Breakdown of points&lt;/div&gt;
&lt;div id="details"&gt;&lt;/div&gt;
&lt;/div&gt;

&lt;/div&gt;
&lt;/body&gt;
&lt;/html&gt;
</pre>
<p>Disregard all the usual markup. Do notice the input element with an ID of <em>inputPassword</em>, the div element with an ID of <em>complexity</em> which shows the complexity of the password and div element with an ID of <em>details</em> which shows the breakdown of points.</p>
<p>We&#8217;ve also included the jQuery library and our own script file. Extra points if you appreciate the name of our script file.</p>
<h3>CSS Styling</h3>
<pre name="code" class="css">
body{
	font-family: "Lucida Grande", "Verdana", sans-serif;
}

h1{
	font-size: 30px;
	padding: 0;
	margin: 0;
}

h2{
	font-size: 18px;
	padding: 0;
	margin: 0 5px 30px 0;
}

input{
	width: 288px;
	height: 30px;
	margin: 50px 0 0 0;
	padding: 3px 5px;
	font-size: 22px;
	font-family: "Lucida Grande", "Verdana", sans-serif;
}

#container{
	width: 820px;
	margin-left: auto;
	margin-right: auto;
	padding: 50px 0 0 0;
}

.block{
	width: 300px;
	margin: 0 auto 0 auto;
}

#complexity, #results{
	width: 300px;
	padding: 3px 0;
	height: 20px;
	color: #000;
	font-size: 14px;
	text-align: center;
}

#results{
	margin: 30px 0 20px 0;
}

.default{background-color: #CCC;}
.weak{background-color: #FF5353;}
.strong{background-color: #FAD054;}
.stronger{background-color: #93C9F4; }
.strongest{background-color: #B6FF6C;}

span.value{
	font-weight:bold;
	float: right;
}
</pre>
<p>Just boiler plate CSS for layouts and typography. We do have a bunch of classes at the bottom for each individual strength ratings. We&#8217;ll add them to the elements when needed.</p>
<h3>JavaScript Implementation</h3>
<p>Now that we have a solid framework and some basic styling in place, we can start coding up the required functionality. Do note that we make extensive use of jQuery. Feel free to link to Google&#8217;s CDN if necessary.</p>
<h3>Variables and Event Handling</h3>
<p>Since a lot of number juggling is going to go on, we need a bunch of variables to hold the values. Since is a demo and not production code, I&#8217;d decided to declare the variables as global and access them through the helper methods instead of declaring them internally and then passing it to the functions.</p>
<pre name="code" class="js">
	var strPassword;
	var charPassword;
	var complexity = $("#complexity");
	var minPasswordLength = 8;
	var baseScore = 0, score = 0;

	var num = {};
	num.Excess = 0;
	num.Upper = 0;
	num.Numbers = 0;
	num.Symbols = 0;

	var bonus = {};
	bonus.Excess = 3;
	bonus.Upper = 4;
	bonus.Numbers = 5;
	bonus.Symbols = 5;
	bonus.Combo = 0;
	bonus.FlatLower = 0;
	bonus.FlatNumber = 0;
</pre>
<p>The variable names are pretty standard fare but I&#8217;d give a rundown anyway. <em>strPassword</em> holds the input box&#8217;s value, <em>charPassword</em> is an array holding each character of the string, <em>complexity</em> holds a reference to the div element. We also define the minimum password length, score and the base score.</p>
<p>We create a quick hash to hold the number of extra characters, upper case characters, numbers and symbols. We do the same for the bonuses. The <em>num</em> hash holds the number of characters while the <em>bonus</em> hash holds the bonus multipliers. You can just create individual variables but I think this looks cleaner. </p>
<p>Don&#8217;t forget to hook up the event handler to the event. </p>
<pre name="code" class="js">
	$("#inputPassword").bind("keyup", checkVal);
</pre>
<p><em>checkVal</em> is the event handler which we&#8217;ll create in just a tiny bit.</p>
<h3>The Event Handler</h3>
<pre name="code" class="js">
function checkVal()
{
	if (charPassword.length >= minPasswordLength)
	{
		baseScore = 50;
		analyzeString();
		calcComplexity();
	}
	else
	{
		baseScore = 0;
	}

	outputResult();
}
</pre>
<p>We first check the length of the input string. If it&#8217;s greater than or equal to the minimum specified length, we can proceed. We set the base score to 50 and call the helper methods which take care of analyzing the string and computing it&#8217;s complexity.</p>
<p>If it&#8217;s less than the expected length, we just set the base score to 0.</p>
<p>We then call the <em>outputResult</em> function which takes care of making sense of the computed computations. We&#8217;ll see how it works later below.</p>
<h3>Analyzing the Input</h3>
<pre name="code" class="js">
function analyzeString ()
{
	for (i=0; i&lt;charPassword.length;i++)
	{
		if (charPassword[i].match(/[A-Z]/g)) {num.Upper++;}
		if (charPassword[i].match(/[0-9]/g)) {num.Numbers++;}
		if (charPassword[i].match(/(.*[!,@,#,$,%,^,&#038;,*,?,_,~])/)) {num.Symbols++;}
	}

	num.Excess = charPassword.length - minPasswordLength;

	if (num.Upper &#038;&#038; num.Numbers &#038;&#038; num.Symbols)
	{
		bonus.Combo = 25;
	}

	else if ((num.Upper &#038;&#038; num.Numbers) || (num.Upper &#038;&#038; num.Symbols) || (num.Numbers &#038;&#038; num.Symbols))
	{
		bonus.Combo = 15;
	}

	if (strPassword.match(/^[\sa-z]+$/))
	{
		bonus.FlatLower = -15;
	}

	if (strPassword.match(/^[\s0-9]+$/))
	{
		bonus.FlatNumber = -35;
	}
}
</pre>
<p>This maybe look a bit complicated but I promise you, it&#8217;s only because of the regular expressions. Let&#8217;s go over the code part by part.</p>
<p>First, we need to figure out the composition of the string in question. As in, we need to figure out whether the string contains upper case letters, numbers of symbols and if so, how many of them are present. With this in mind, we iterate through the character array and check each characters to see its type. The <em>match</em> method lets us match a string against a regular expression. If you are new to regular expression, I suggest you read Vasili&#8217;s great article <a href="http://net.tutsplus.com/tutorials/other/8-regular-expressions-you-should-know/">here</a>.</p>
<p>Next, we have determine the difference between the length of the input string and the specified minimum length of the password. This gives us the excess number of characters to play around with.</p>
<p>We then check if the string has upper case, numbers and symbols. If so, grant a bonus. We also check to see whether it has combinations of two of them and grant a smaller bonus if so.</p>
<p>Finally, we check to see whether a string is flat: whether it contains only lower case letters or only numbers. We check this with a regular expression and if so, penalize the password for this practice.</p>
<h3>Calculate the Complexity</h3>
<pre name="code" class="js">
function calcComplexity()
{
	score = baseScore + (num.Excess*bonus.Excess) + (num.Upper*bonus.Upper) + (num.Numbers*bonus.Numbers) +
(num.Symbols*bonus.Symbols) + bonus.Combo + bonus.FlatLower + bonus.FlatNumber;
}
</pre>
<p>Just a simple addition. We add the base score to the product of the number of excess characters and it&#8217;s multiplier. Same for upper case letters, numbers and symbols. We then add a bonus for combinations, if present, and add penalties if the string is flat. </p>
<h3>Updating the UI</h3>
<p>Now that all the computation is behind us, we can update the UI to reflect the changes. Here are each of the states.</p>
<div class="tutorial_image">
   <img src="http://nettuts.s3.amazonaws.com/483_password/images/weak.png" alt="Points" />
</div>
<div class="tutorial_image">
   <img src="http://nettuts.s3.amazonaws.com/483_password/images/average.png" alt="Points" />
</div>
<div class="tutorial_image">
   <img src="http://nettuts.s3.amazonaws.com/483_password/images/strong.png" alt="Points" />
</div>
<div class="tutorial_image">
   <img src="http://nettuts.s3.amazonaws.com/483_password/images/secure.png" alt="Points" />
</div>
<pre name="code" class="js">
function outputResult()
{
	if ($("#inputPassword").val()== "")
	{
		complexity.html("Enter a random value").addClass("default");
	}
	else if (charPassword.length &lt; minPasswordLength)
	{
		complexity.html("At least " + minPasswordLength+ " characters please!").addClass("weak");
	}
	else if (score&lt;50)
	{
		complexity.html("Weak!").addClass("weak");
	}
	else if (score&gt;=50 &#038;&#038; score&lt;75)
	{
		complexity.html("Average!").addClass("strong");
	}
	else if (score&gt;=75 &#038;&#038; score&lt;100)
	{
		complexity.html("Strong!").addClass("stronger");
	}
	else if (score&gt;=100)
	{
		complexity.html("Secure!").addClass("strongest");
	}
}
</pre>
<p>Nothing fancy here but we&#8217;ll go through it line by line.</p>
<p>We first check to see whether input is empty. If so, change the result&#8217;s text and add a <em>default</em> class to change it&#8217;s background color back to it&#8217;s original gray.</p>
<p>If it&#8217;s less than the minimum specified length, we change the text accordingly and add a <em>weak</em> class so it&#8217;s background is red. We do the same if the total score is less than 50 but change the text to <em>weak</em>.</p>
<p>As the score increases, we change the text accordingly and add the necessary classes. Feel free to change the baseline scores for each rating. I just put in unscientific values to get the demo going.</p>
<h3>Updating the Detailed Breakdown</h3>
<div class="tutorial_image">
   <img src="http://nettuts.s3.amazonaws.com/483_password/images/points.png" alt="Points" />
</div>
<p>With the main result updated, we can look at updating the stats now. </p>
<pre name="code" class="js">
function outputResult()
{
	// Previous Code

    $("#details").html("Base Score :&lt;span class=\"value\"&gt;" + baseScore  + "&lt;/span&gt;"
				  + "&lt;br /&gt;Length Bonus :&lt;span class=\"value\"&gt;" + (num.Excess*bonus.Excess) + " ["+num.Excess+"x"+bonus.Excess+"]&lt;/span&gt; "
				  + "&lt;br /&gt;Upper case bonus :&lt;span class=\"value\"&gt;" + (num.Upper*bonus.Upper) + " ["+num.Upper+"x"+bonus.Upper+"]&lt;/span&gt; "
				  + "&lt;br /&gt;Number Bonus :&lt;span class=\"value\"&gt; " + (num.Numbers*bonus.Numbers) + " ["+num.Numbers+"x"+bonus.Numbers+"]&lt;/span&gt;"
				  + "&lt;br /&gt;Symbol Bonus :&lt;span class=\"value\"&gt; " + (num.Symbols*bonus.Symbols) + " ["+num.Symbols+"x"+bonus.Symbols+"]&lt;/span&gt;"
				  + "&lt;br /&gt;Combination Bonus :&lt;span class=\"value\"&gt; " + bonus.Combo + "&lt;/span&gt;"
				  + "&lt;br /&gt;Lower case only penalty :&lt;span class=\"value\"&gt; " + bonus.FlatLower + "&lt;/span&gt;"
				  + "&lt;br /&gt;Numbers only penalty :&lt;span class=\"value\"&gt; " + bonus.FlatNumber + "&lt;/span&gt;"
				  + "&lt;br /&gt;Total Score:&lt;span class=\"value\"&gt; " + score  + "&lt;/span&gt;"
}
</pre>
<p>This part is not as confusing as it looks. Let me explain.</p>
<p>Instead of just updating the individual values for the detailed results, I&#8217;ve resorted to just updating the complete HTML value of the container. I know it is going to be sluggish when a number of these boxes add up but accessing each element individually and then updating it&#8217;s value for a tiny demo seemed to be rather counter-productive. So run with me here. </p>
<p>This is just like injecting regular HTML into an element except that we&#8217;ve placed a couple variables inside to enable the details to be updated instantaneously. Each value gets a <em>value</em> class to make it bold. We also display the number of special characters and it&#8217;s multipler so the user can gauge which elements get more weightage.</p>
<h3>A few Tweaks</h3>
<p>At this point of time, there are 2 bugs which show up. </p>
<ul>
<li>If you type in a long password and then erase the text box, the background colors don&#8217;t change back.</li>
<li>In the same scenario, the details of the points break down don&#8217;t update as it should.</li>
</ul>
<p>We&#8217;ll tackle them one by one.</p>
<p>For the first bug, the root cause happens to be the fact that we don&#8217;t remove all the other classes. This wouldn&#8217;t be a problem if the most recently added classes takes precedence over others. Unfortunately, it&#8217;s not so. Here is a quick fix.</p>
<pre name="code" class="js">
function outputResult()
{
	if ($("#inputPassword").val()== "")
	{ complexity.html("Enter a random value").removeClass("weak strong stronger strongest").addClass("default");}
	else if (charPassword.length &lt; minPasswordLength)
	{complexity.html("At least " + minPasswordLength+ " characters please!").removeClass("strong stronger strongest").addClass("weak");}
	else if (score&lt;50)
	{complexity.html("Weak!").removeClass("strong stronger strongest").addClass("weak");}
	else if (score&gt;=50 &#038;&#038; score&lt;75)
	{complexity.html("Average!").removeClass("stronger strongest").addClass("strong");}
	else if (score&gt;=75 &#038;&#038; score&lt;100)
	{complexity.html("Strong!").removeClass("strongest").addClass("stronger");}
	else if (score&gt;=100)
	{complexity.html("Secure!").addClass("strongest");}

	// Details updating code
}
</pre>
<p>You are probably asking why we don&#8217;t remove each and every class here. The answer is simple: we take advantage of one of the primary attributes of CSS: <em>cascading</em>. If you note the order of declaration of each class in the CSS file you&#8217;ll notice that <em>default</em> occurs the first and <em>strongest</em> comes the last which means if an element has the <em>strongest</em> class it&#8217;ll override any modifications made by any class above it. So we&#8217;ll have to only remove classes which occur below the relevant class. For example, for an element to have <em>strong</em>, we&#8217;ll have to remove the <em>stronger</em> and <em>strongest</em> classes. </p>
<p>The reason the second bug exist is due to the fact that the individuals variables aren&#8217;t reset when a new event occurs. They carry over to the next event as well. In order to fix this, we create a quick function which reinitializes all the relevant variables and add it the <em>checkVal</em> event handler so it is called every time the input box&#8217;s text is updated.</p>
<pre name="code" class="js">
function init()
{
	strPassword= $("#inputPassword").val();
	charPassword = strPassword.split("");

	num.Excess = 0;
	num.Upper = 0;
	num.Numbers = 0;
	num.Symbols = 0;
	bonus.Combo = 0;
	bonus.FlatLower = 0;
	bonus.FlatNumber = 0;
	baseScore = 0;
	score =0;
}
</pre>
<pre name="code" class="js">
function checkVal()
{
	init();

	// Other code
}
</pre>
<h3>Limitations</h3>
<div class="tutorial_image">
   <img src="http://nettuts.s3.amazonaws.com/483_password/images/limitation.png" alt="Limitation with the current implementation" />
</div>
<p>If you&#8217;ve been playing around with the demo a bit, you&#8217;ll notice that <em>Pa$$W0rd$</em> turns up as a secure password while in fact it&#8217;ll be broken pretty soon. This is due to the simplicity of our algorithm here. We don&#8217;t check for character replacements. Or common passwords or patterns for that matter. Doing such things would increase the difficulty of this tutorial while reducing its approachability, both of which I didn&#8217;t want for this particular write up. </p>
<p>This is intended as a basic password strength checker. If you need to beef it up, you could probably add a couple more regular expressions to check for patterns and character repetition and then tune the results accordingly.</p>
<p>Looking the input up against a dictionary is really out of the scope of this article and would require either a huge dictionary downloaded to the client side or hooking it up to a server side system to do that. Again, I really wanted to avoid both of them this time.</p>
<h3>Conclusion</h3>
<p>And there you have it: how to add a user friendly functionality, the ability to let the user know the strength of a password he just entered, to your projects. Hopefully you&#8217;ve found this tutorial interesting and this has been useful to you. Feel free to reuse this code elsewhere in your projects and chime in here if you are running into difficulties.</p>
<p>Questions? Nice things to say? Criticisms? Hit the comments section and leave me a comment. Happy coding!</p>
<ul class="webroundup">
<li>Follow us on <a href="http://www.twitter.com/nettuts">Twitter</a>, or subscribe to the <a href="http://feeds.feedburner.com/nettuts" title="Nettuts+ RSS Feed">Nettuts+ RSS Feed</a> for the best web development tutorials on the web.</li>
</ul>
<p>
<script type="text/javascript"><!--digg_url = "post permalink (not digg url)"; // -->
</script><br />
<script src="http://digg.com/tools/diggthis.js" type="text/javascript"></script></p>
]]></content:encoded>
			<wfw:commentRss>http://net.tutsplus.com/tutorials/javascript-ajax/build-a-simple-password-strength-checker/feed/</wfw:commentRss>
		<slash:comments>65</slash:comments>
		</item>
		<item>
		<title>Simple Draggable Element Persistence with jQuery</title>
		<link>http://net.tutsplus.com/tutorials/javascript-ajax/simple-draggable-element-persistence-with-jquery/</link>
		<comments>http://net.tutsplus.com/tutorials/javascript-ajax/simple-draggable-element-persistence-with-jquery/#comments</comments>
		<pubDate>Thu, 29 Oct 2009 19:27:18 +0000</pubDate>
		<dc:creator>Dustin Blake</dc:creator>
				<category><![CDATA[JavaScript & AJAX]]></category>
		<category><![CDATA[drag]]></category>
		<category><![CDATA[draggable]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[jQuery]]></category>
		<category><![CDATA[jQuery ui]]></category>

		<guid isPermaLink="false">http://net.tutsplus.com/?p=7474</guid>
		<description><![CDATA[<img src="http://nettuts.s3.amazonaws.com/477_drag/200x200.jpg" alt="Simple Draggable Element Persistence with jQuery width="200" height="200"/>]]></description>
			<content:encoded><![CDATA[<p>At some point you may need to create a draggable element within your web application.  This is great functionality, however  you may want or find that you need the element to stay in place after being dragged around.  In this tutorial I will show you how to easily drag an element and make it stick, even after a page reload, by grabbing and storing its X and Y coordinates.</p>
<p><span id="more-7474"></span></p>
<div class="tutorial_image">
<a href="http://nettuts.s3.amazonaws.com/477_drag/source.zip"><img src="http://nettuts.com/wp-content/themes/nettuts/site_images/button_src_nm.jpg"></a>
</div>
<h3>Scenario</h3>
<p>So you have an element in your web application.  You can drag it around, put it here and put it there.  But, when the page is reloaded in any way, the element returns to its default position.  While you want the element to be draggable, you don&#8217;t want it to move after its been dragged.  Let&#8217;s look at a simple solution to give us this ability.</p>
<h3>Getting Started</h3>
<p>For this tutorial we are going to need the <a href="http://jquery.com" target="_blank" title="jQuery: write less, do more">jQuery library</a>, <a href="http://jqueryui.com" target="_blank" title="jQuery: user interface">jQuery UI</a>, and the <a href="http://code.google.com/p/jquery-json/" target="_blank" title="jQuery-JSON Plugin @ Google Code">jQuery-JSON</a> plugin by <a href="http://twitter.com/deadwisdom" target="_blank" title="Brantley Harris @ Twitter">Brantley Harris</a>. We will also be using some PHP and a MySQL database to parse and store our data. If your new to jQuery, no worries.  jQuery is a highly extensible, fast, and lightweight JavaScript library which is both fun and easy to use.  The library has very nicely structured documentation, and a huge community.  This is my first tutorial on jQuery and JavaScript, so please bear with me.  I hope to explain everything as best as I can and if you have any questions, please feel free to ask.</p>
<div class="tutorial_image"><img src="http://nettuts.s3.amazonaws.com/477_drag/jquery.jpg" border="0" /></div>
<h3>The HTML amd CSS</h3>
<p>I wanted to start off with the HTML and styling for this tutorial since the effect is applyed to HTML elements, it helps to visualize what we are going to do, right off the bat. First the CSS:</p>
<pre name="code" class="css">
html, body {
	background:#151515;
	margin:0 0 0 0;
	padding:0 0 0 0;
}

#glassbox {
	background:#333;
	border:1px solid #000;
	height:400px;
	margin:30px auto auto auto;
	position:relative;
	width:960px;
	-moz-border-radius: 10px;
	-webkit-border-radius: 10px;
}

#element {
	background:#666;
	border:1px #000 solid;
	cursor:move;
	height:143px;
	padding:10px 10px 10px 10px;
	width:202px;
	-moz-border-radius: 10px;
	-webkit-border-radius: 10px;
}

#respond{
	color:#fff;
	margin:0 auto 0 auto;
	width:960px;
}
</pre>
<p>The CSS is very simple.  We set the html and body properties to clear margins and padding, and continue by setting some heights, widths, and other properties to our elements so it doesn&#8217;t look so bland.  -moz-border-radius and -webkit-border-radius are two properties which allow us to create rounded borders (applicable only to Mozilla Firefox and Safari 3 at the moment) for our elements.  Let&#8217;s take a look at the HTML:</p>
<pre name="code" class="html">
&lt;!DOCTYPE html>
&lt;html>
&lt;head>
&lt;meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
&lt;title>Simple Draggable Element Persistence with jQuery&lt;/title>

&lt;link rel="stylesheet" href="style.css" type="text/css" />
&lt;script type="text/javascript" src="js/jquery-1.3.2.min.js">&lt;/script>
&lt;script type="text/javascript" src="js/jquery-ui-1.7.2.custom.min.js">&lt;/script>
&lt;script type="text/javascript" src="js/jquery.json-2.2.min.js">&lt;/script>

&lt;/head>

&lt;body>

	&lt;div id="glassbox">
		&lt;div id="element">&lt;img src="nettuts.jpg" alt="Nettuts+" />Move the Box&lt;p>&lt;/p>&lt;/div>
	&lt;/div>

	&lt;div id="respond">&lt;/div>
</pre>
<p>As you can see we just setup a very nice and simple page which calls in our CSS, JavaScript library and plugins, and contains the elements which we will be using to apply some effects and events to. As a note,the jquery-ui file is a custom build which only includes the core and the draggable interaction functionality.</p>
<div class="tutorial_image"><img src="http://nettuts.s3.amazonaws.com/477_drag/general.jpg" border="0" /></div>
<h3>The Javascript</h3>
<p>Now for some juicy interaction! Lets first take a look at some of the basic functions we will be using to apply some effects to our elements. Let&#8217;s tear it down.</p>
<pre name="code" class="js">
&lt;script type="text/javascript">
	$(document).ready(function() {
		$("#element").draggable({
				containment: '#glassbox',
				scroll: false
		 })
</pre>
<p>First we tell the browser, &#8220;Hey, this is some code we want to run; it&#8217;s not HTML, it&#8217;s JavaScript.&#8221;  We then want to wait for the document to load before we do anything else, once thats happened, we call a function to select our #element DIV, and add the draggable handler with some basic options.  The containment options will keep our element within the parent DIV, and we set scroll to false because we don&#8217;t want any scrolling to happen.  Let&#8217;s move on:</p>
<pre name="code" class="js">
	.mousemove(function(){
		var coord = $(this).position();
		$("p:last").text( "left: " + coord.left + ", top: " + coord.top );
	})
</pre>
<p>With this tidbit, we call the event handler mousemove and tell it, &#8220;When the mouse moves, set the variable &#8216;coord&#8217; to equal our selected #element&#8217;s position.&#8221;  Then we select a paragraph (&#8221;p:last&#8221;), the last one in #element, and print some text which will read out the left(x) and the top(y) properties of our element relative to the parent object (which is #glassbox).</p>
<pre name="code" class="js">
	.mouseup(function(){
				var coords=[];
				var coord = $(this).position();
				var item={ coordTop:  coord.left, coordLeft: coord.top  };
			   	coords.push(item);
				var order = { coords: coords };
				$.post('updatecoords.php', 'data='+$.toJSON(order), function(response){
						if(response=="success")
							$("#respond").html('&lt;div class="success">X and Y Coordinates Saved!&lt;/div>').hide().fadeIn(1000);
							setTimeout(function(){ $('#respond').fadeOut(1000); }, 2000);
						});
				});

	});
&lt;/script>
</pre>
<p>Ok now for some devilry!  In this snippet we are going to do a couple of things.  First we want to setup an empty array, and then get some values to fill it with.  By calling the event handler .mouseup() we are telling the browser to look for the event when you unclick your mouse.  We set the variable coords to equal our empty array, and again set the variable coord to equal the position handler of our #element.  Then we need to create a list of items, these will be coordTop: and coordLeft: respectfully equaling our #element&#8217;s left and top positions.  With coords.push(item) we are literally pushing our item list and filling the coords array with it.  Then set the variable order as a new list where the coords key will equal our coords array.  Now for some AJAX.</p>
<div class="tutorial_image"><img src="http://nettuts.s3.amazonaws.com/477_drag/dragged.jpg" border="0" /></div>
<p>$.post is an AJAX request handler which loads a remote page using an HTTP POST method.  This function looks for the parameters: url, data, callback and data type to be returned.  In this tutorial we specify the updatecoords.php file as our URL because this is where we want to send our post data, we then define our datatype by including the $.toJSON function defined in our jquery-JSON plugin and setting our variable order as the data to be handled by .toJSON.  Next we create a callback which checks for a return response from our PHP file upon success, and add a bit of flavor by saying, &#8220;If whats returned is equal to success then&#8230;&#8221;  We keep this html hidden by using the effect handler .hide, and tell it to fade in at 1000 milliseconds, wait with a timeout for 2000 milliseconds, and tell it to fade out again. In the end our JavaScript should look like this:</p>
<pre name="code" class="js">
&lt;script type="text/javascript">
	$(document).ready(function() {
		$("#element").draggable({
				containment: '#glassbox',
				scroll: false
		 }).mousemove(function(){
				var coord = $(this).position();
				$("p:last").text( "left: " + coord.left + ", top: " + coord.top );
		 }).mouseup(function(){
				var coords=[];
				var coord = $(this).position();
				var item={ coordTop:  coord.left, coordLeft: coord.top  };
			   	coords.push(item);
				var order = { coords: coords };
				$.post('updatecoords.php', 'data='+$.toJSON(order), function(response){
						if(response=="success")
							$("#respond").html('&lt;div class="success">X and Y Coordinates Saved!&lt;/div>').hide().fadeIn(1000);
							setTimeout(function(){ $('#respond').fadeOut(1000); }, 2000);
						});
				});

		});
&lt;/script>
</pre>
<p>Place the JavaScript below the HTML, right after the closing body tag.</p>
<h3>The PHP</h3>
<p>Alright, now lets get to business on doing something with the data being posted from our jQuery.  First lets create a simple database to store our coordinates, which we will then later retrieve to define the position of our element.  Second will be our config.php file which will store our database connection settings, and then we will finish with updatecords.php.</p>
<pre name="code" class="sql">
Database: 'xycoords'

CREATE TABLE IF NOT EXISTS `coords` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `x_pos` int(4) NOT NULL,
  `y_pos` int(4) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1;
</pre>
<p>config.php</p>
<pre name="code" class="php">
&lt;?php
/*Database Settings*/

$db_host ="localhost"; //this will likely stay the same
$db_name = "xycoords"; //name of the database we will be using
$db_usr = "database_username"; //db username
$db_pass = "database_password"; //db password

//Connect to the database
$link = mysqli_connect($db_host, $db_usr, $db_pass) or die("MySQL Error: " . mysqli_error());
//Select our database
mysqli_select_db($link, $db_name) or die("MySQL Error: " . mysqli_error());
?>
</pre>
<p>updatecoords.php</p>
<pre name="code" class="php">
&lt;?php
if(!$_POST["data"]){
	echo "Nothing Sent";
	exit;
}

include ('config.php');

//decode JSON data received from AJAX POST request
$data = json_decode($_POST["data"]);

foreach($data->coords as $item) {
	//Extract X number for panel
	$coord_X = preg_replace('/[^\d\s]/', '', $item->coordTop);
	//Extract Y number for panel
	$coord_Y = preg_replace('/[^\d\s]/', '', $item->coordLeft);
	//escape our values - as good practice
	$x_coord = mysqli_real_escape_string($link, $coord_X);
	$y_coord = mysqli_real_escape_string($link, $coord_Y);

	//Setup our Query
	$sql = "UPDATE coords SET x_pos = '$x_coord', y_pos = '$y_coord'";

	//Execute our Query
	mysqli_query($link, $sql) or die("Error updating Coords :".mysqli_error());
}

//Return Success
echo "success";

?>
</pre>
<p>This is pretty simple to follow.  The first thing we want to do is check to make sure our post data is being passed to the file.  If that happens we include our config file for our database connection and set the variable $data to json_decode(passed post variable);  <a href="http://us.php.net/manual/en/function.json-decode.php" target="_blank" title="json_decode @ php.net">json_decode</a> is a PHP function implemented in PHP 5.2.0 which allows us to decode a JSON string.</p>
<p>Since our $data variable contains an array of data, we need to tear it apart to get the values we need.  To do this we take foreach $data->coords (which is from our order variable in our JavaScript) as an item.  This takes each key and value pair and creates an item object from the array, we then specify and create a variable out of it.  We use this in conjunction with preg_replace so that we can take out the characters we don&#8217;t need.  We then, as good practice and a measure of security, escape our values to prepare them for insertion into the database.  If all goes well, we need to return success to our JavaScript to let it know everything went just fine.</p>
<div class="tutorial_image"><img src="http://nettuts.s3.amazonaws.com/477_drag/response.jpg" border="0" /></div>
<h3>Lastly</h3>
<p>Now that we have what we need in place, to grab the position coordinates from our element and pass it to PHP for storing, we need to modify our HTML to reflect the position of our element.  To do this we change the basic element HTML and instead create it with PHP:</p>
<pre name="code" class="php">
&lt;div id="glassbox">
&lt;?php
		//Create a query to fetch our values from the database
		$get_coords = mysqli_query($link, "SELECT * FROM coords");
		//We then set variables from the * array that is fetched from the database
        while($row = mysqli_fetch_array($get_coords)) {
			$x = $row['x_pos'];
			$y = $row['y_pos'];
			//then echo our div element with CSS properties to set the left(x) and top(y) values of the element
			echo '&lt;div id="element" style="left:'.$x.'px; top:'.$y.'px;">&lt;img src="nettuts.jpg" alt="Nettuts+" />Move the Box&lt;p>&lt;/p>&lt;/div>';
		}
?>
&lt;/div>
&lt;div id="respond">&lt;/div>
</pre>
<p>Here we setup a basic query to the database to select all the rows from the table coords.  We then invoke a while loop which specifies each row we select as $row.  Now we can set some variables to equal each individual row we pull from the database, and echo them in the proper place within the elements style (left and top).</p>
<h3>Wrapping up</h3>
<p>Well I hope that you enjoyed this tutorial as much as I did writing it! It may not be perfect.  While this is just one way to get this functionality in a draggable element, there are other ways (and perhaps better) to achieve it.  Once such way could be to store the coordinate values in a cookie, to keep calls to the database at a minimum.  You could also serialize the values passed from jQuery to PHP instead of using JSON.  This tutorial is just one example from which you can expand upon. Thanks for reading!</p>
<ul class="webroundup">
<li>Follow us on <a href="http://www.twitter.com/nettuts">Twitter</a>, or subscribe to the <a href="http://feeds.feedburner.com/nettuts" title="Nettuts+ RSS Feed">Nettuts+ RSS Feed</a> for the best web development tutorials on the web.</li>
</ul>
<p>
<script type="text/javascript"><!--digg_url = "post permalink (not digg url)"; // -->
</script><br />
<script src="http://digg.com/tools/diggthis.js" type="text/javascript"></script></p>
]]></content:encoded>
			<wfw:commentRss>http://net.tutsplus.com/tutorials/javascript-ajax/simple-draggable-element-persistence-with-jquery/feed/</wfw:commentRss>
		<slash:comments>61</slash:comments>
		</item>
		<item>
		<title>Learn how to Create a Retro Animated Flip-Down Clock</title>
		<link>http://net.tutsplus.com/tutorials/html-css-techniques/learn-how-to-create-a-retro-animated-flip-down-clock/</link>
		<comments>http://net.tutsplus.com/tutorials/html-css-techniques/learn-how-to-create-a-retro-animated-flip-down-clock/#comments</comments>
		<pubDate>Wed, 21 Oct 2009 18:48:38 +0000</pubDate>
		<dc:creator>Alexandru Pitea</dc:creator>
				<category><![CDATA[HTML & CSS]]></category>
		<category><![CDATA[JavaScript & AJAX]]></category>
		<category><![CDATA[clock]]></category>
		<category><![CDATA[MooTools]]></category>

		<guid isPermaLink="false">http://net.tutsplus.com/?p=7313</guid>
		<description><![CDATA[<img src="http://nettuts.s3.amazonaws.com/470_clock/preview.jpg" alt="Create an Animated Flip Down Clock" width="200" height="200"/>]]></description>
			<content:encoded><![CDATA[<p>In this tutorial, we will create an animated flip down clock inspired by the 70&#8217;s. Using the Mootools framework, I tried to replicate the flip action of the pads and make it as lifelike as possible. With it&#8217;s retro styling, it could be a really neat thing to add to your website, so let&#8217;s get started! </p>
<p><span id="more-7313"></span></p>
<div class="tutorial_image">
<a href="http://nettuts.s3.amazonaws.com/470_clock/Source/Source.zip"><img src="http://nettuts.com/wp-content/themes/nettuts/site_images/button_src_nm.jpg"></a><br />
<a href="http://nettuts.s3.amazonaws.com/470_clock/Source/index.html"><img src="http://nettuts.com/wp-content/themes/nettuts/site_images/button_demo_nm.jpg"></a>
</div>
<h3>Tutorial Details</h3>
<ul>
<li><b>Program</b>: Mootools </li>
<li><b>Difficulty:</b> Easy </li>
<li><b>Estimated Completion Time:</b> ~ 1 hour </li>
</ul>
<div class="tutorial_image"><img src="http://nettuts.s3.amazonaws.com/470_clock/0.jpg" border="0" /></div>
<h3>Step 1: The Main Concept</h3>
<p>The clock is composed of three groups of images: hours, minutes and seconds, which are split in an upper part and a lower part so we can obtain the &#8220;flip&#8221; effect. The main animation consists of reducing the height of the upper part from 100% to 0%, then increasing the height of the lower part from 0% to 100% for each group in which a digit changes. Here is the basic scheme.</p>
<div class="tutorial_image"><img src="http://nettuts.s3.amazonaws.com/470_clock/1.jpg" border="0" /></div>
<h3>Step 2: Photoshop</h3>
<p>First, we must create our images. </p>
<p>
Select the &#8220;Rounded Ractangle Tool&#8221; (U), set the radius to 10px and the color to #0a0a0a and create a 126px by 126px ractangle, you can change the dimension according to your needs, just keep them an even number. Resterize the shape by going to Layer > Rasterize > Shape or Right Click > Rasterize Layer. Now we want to create that &quot;gap&quot; between the two parts and make the upper background a little bit lighter. Place a guide line at the horizontal half of our pad, then select the hole pad (Ctrl + Click on the layer icon) and with the Rectangular Marquee Tool (M) select the upper half in intersect mode (hold Shift + Alt). Now we just have to fill the selection with #121212 using the Paint Bucket Tool (G). Next trace a 2px, black line using our guide line as help, on a separate layer.  </p>
<div class="tutorial_image"><img src="http://nettuts.s3.amazonaws.com/470_clock/2.jpg" border="0" /></div>
<p>Now we have to add the digits. Using the Type Tool (T) make a new layer with the digits and place it under the line we&#8217;ve created earlier.</p>
<div class="tutorial_image"><img src="http://nettuts.s3.amazonaws.com/470_clock/3.jpg" border="0" /></div>
<p>Just add a little overlay on the numbers to make them look a bit more realistic. Create a new layer above the digits layer, select the lower part of the pad and fill with #b8b8b8, then fill the upper part with #d7d7d7. Now set the blending mode to &#8220;Multiply&#8221;.   </p>
<div class="tutorial_image"><img src="http://nettuts.s3.amazonaws.com/470_clock/4.jpg" border="0" /></div>
<p>Ok. Now that we have our completed pad, we have to split it up. The main idea is to split the right digit from the left one, so instead of having 60 images for the minutes and seconds groups, you end up with 20 images that we will use for both groups. So basicly we have to split our pad into 4 images with the same dimensions. I used the Crop Tool (C) for this job.</p>
<div class="tutorial_image"><img src="http://nettuts.s3.amazonaws.com/470_clock/5.jpg" border="0" /></div>
<p>After you crop the pad, change the digit and save each time as a separate .png so you end up with all the files you need ( numbers from 0 &#8211; 9 ). Repeat this step for all parts of the pad. Note that for the hours pad, you don&#8217;t separate the digits, you have just the upper and lower part. In the end here is our folder structure (&quot;Double&quot; for minutes and seconds, &quot;Single&quot; for hours): </p>
<div class="tutorial_image"><img src="http://nettuts.s3.amazonaws.com/470_clock/6.jpg" border="0" /></div>
<h3>Step 3: HTML Markup</h3>
<p>Now that we have our files ready we can start coding. First of all, we need two containers for our images, one for the &quot;upperPart&quot; of our clock and one for the &quot;lowerPart&quot;.</p>
<pre name="code" class="html">
&lt;div id=&quot;upperPart&quot;&gt;
&lt;/div&gt;

&lt;div id=&quot;lowerPart&quot;&gt;
&lt;/div&gt;
</pre>
<p>Next we add the images. Here is a scheme with the id&#8217;s I&#8217;ve used:</p>
<div class="tutorial_image"><img src="http://nettuts.s3.amazonaws.com/470_clock/7.jpg" border="0" /></div>
<pre name="code" class="html">
&lt;div id=&quot;upperPart&quot;&gt;
    &lt;img src=&quot;spacer.png&quot; /&gt;&lt;img id=&quot;hoursUp&quot; src=&quot;Single/Up/AM/0.png&quot; /&gt;
    &lt;img id=&quot;minutesUpLeft&quot; src=&quot;Double/Up/Left/0.png&quot; /&gt;&lt;img id=&quot;minutesUpRight&quot; src=&quot;Double/Up/Right/0.png&quot; /&gt;
    &lt;img id=&quot;secondsUpLeft&quot; src=&quot;Double/Up/Left/0.png&quot; /&gt;&lt;img id=&quot;secondsUpRight&quot; src=&quot;Double/Up/Right/0.png&quot; /&gt;
&lt;/div&gt;
&lt;div id=&quot;lowerPart&quot;&gt;
    &lt;img src=&quot;spacer.png&quot; /&gt;&lt;img id=&quot;hoursDown&quot; src=&quot;Single/Down/AM/0.png&quot;/&gt;
    &lt;img id=&quot;minutesDownLeft&quot; src=&quot;Double/Down/Left/0.png&quot; /&gt;&lt;img id=&quot;minutesDownRight&quot; src=&quot;Double/Down/Right/0.png&quot; /&gt;
    &lt;img id=&quot;secondsDownLeft&quot; src=&quot;Double/Down/Left/0.png&quot; /&gt;&lt;img id=&quot;secondsDownRight&quot; src=&quot;Double/Down/Right/0.png&quot; /&gt;
&lt;/div&gt;
</pre>
<p>I had to use a transparent spacer image that is  1px wide and the same hight as the other images in order to keep the containers from shrinking when the pads flip. Also, there must not be any space between the images from the same group (e.g. &quot;minutesUpLeft&quot; and &quot;minutesUpRight&quot;). </p>
<p>Ok. These will be the front pads of our clock that will flip down, now we have to set up the back ones, so when the front pads flip, the new digits can be seen on the them. We will wrap what we&#8217;ve done so far in a div and just duplicate it above itself, adding to each image id the word &quot;Back&quot; and changing to the appropriate source file.</p>
<pre name="code" class="html">
&lt;div id=&quot;back&quot;&gt;
    &lt;div id=&quot;upperPartBack&quot;&gt;
        &lt;img src=&quot;spacer.png&quot; /&gt;&lt;img id=&quot;hoursUpBack&quot; src=&quot;Single/Up/AM/0.png&quot; /&gt;
        &lt;img id=&quot;minutesUpLeftBack&quot; src=&quot;Double/Up/Left/0.png&quot; /&gt;&lt;img id=&quot;minutesUpRightBack&quot; src=&quot;Double/Up/Right/0.png&quot; /&gt;
        &lt;img id=&quot;secondsUpLeftBack&quot; src=&quot;Double/Up/Left/0.png&quot; /&gt;&lt;img id=&quot;secondsUpRightBack&quot; src=&quot;Double/Up/Right/0.png&quot; /&gt;
    &lt;/div&gt;
    &lt;div id=&quot;lowerPartBack&quot;&gt;
        &lt;img src=&quot;spacer.png&quot; /&gt;&lt;img id=&quot;hoursDownBack&quot; src=&quot;Single/Down/AM/0.png&quot; /&gt;
        &lt;img id=&quot;minutesDownLeftBack&quot; src=&quot;Double/Down/Left/0.png&quot; /&gt;&lt;img id=&quot;minutesDownRightBack&quot; src=&quot;Double/Down/Right/0.png&quot; /&gt;
        &lt;img id=&quot;secondsDownLeftBack&quot; src=&quot;Double/Down/Left/0.png&quot; /&gt;&lt;img id=&quot;secondsDownRightBack&quot; src=&quot;Double/Down/Right/0.png&quot; /&gt;
    &lt;/div&gt;
&lt;/div&gt;

&lt;div id=&quot;front&quot;&gt;
    &lt;div id=&quot;upperPart&quot;&gt;
        &lt;img src=&quot;spacer.png&quot; /&gt;&lt;img id=&quot;hoursUp&quot; src=&quot;Single/Up/AM/0.png&quot; /&gt;
        &lt;img id=&quot;minutesUpLeft&quot; src=&quot;Double/Up/Left/0.png&quot; /&gt;&lt;img id=&quot;minutesUpRight&quot; src=&quot;Double/Up/Right/0.png&quot; /&gt;
        &lt;img id=&quot;secondsUpLeft&quot; src=&quot;Double/Up/Left/0.png&quot; /&gt;&lt;img id=&quot;secondsUpRight&quot; src=&quot;Double/Up/Right/0.png&quot; /&gt;
    &lt;/div&gt;
    &lt;div id=&quot;lowerPart&quot;&gt;
        &lt;img src=&quot;spacer.png&quot; /&gt;&lt;img id=&quot;hoursDown&quot; src=&quot;Single/Down/AM/0.png&quot; /&gt;
        &lt;img id=&quot;minutesDownLeft&quot; src=&quot;Double/Down/Left/0.png&quot; /&gt;&lt;img id=&quot;minutesDownRight&quot; src=&quot;Double/Down/Right/0.png&quot; /&gt;
        &lt;img id=&quot;secondsDownLeft&quot; src=&quot;Double/Down/Left/0.png&quot; /&gt;&lt;img id=&quot;secondsDownRight&quot; src=&quot;Double/Down/Right/0.png&quot; /&gt;
    &lt;/div&gt;
&lt;/div&gt;
</pre>
<p>Here is the complete .html file with reference to the stylesheet and the javascript file &quot;animate.js&quot; in which we will create the animation.</p>
<pre name="code" class="html">
&lt;html&gt;
&lt;head&gt;
&lt;title&gt;Create an Animated Flip Down Clock&lt;/title&gt;
&lt;link rel=&quot;stylesheet&quot; type=&quot;text/css&quot; href=&quot;style.css&quot; /&gt;
&lt;/head&gt;
&lt;body&gt;

&lt;div id=&quot;wrapper&quot;&gt;
	&lt;div id=&quot;back&quot;&gt;
		&lt;div id=&quot;upperPartBack&quot;&gt;
			&lt;img src=&quot;spacer.png&quot; /&gt;&lt;img id=&quot;hoursUpBack&quot; src=&quot;Single/Up/AM/0.png&quot; /&gt;
			&lt;img id=&quot;minutesUpLeftBack&quot; src=&quot;Double/Up/Left/0.png&quot; /&gt;&lt;img id=&quot;minutesUpRightBack&quot; src=&quot;Double/Up/Right/0.png&quot; /&gt;
			&lt;img id=&quot;secondsUpLeftBack&quot; src=&quot;Double/Up/Left/0.png&quot; /&gt;&lt;img id=&quot;secondsUpRightBack&quot; src=&quot;Double/Up/Right/0.png&quot; /&gt;
		&lt;/div&gt;
		&lt;div id=&quot;lowerPartBack&quot;&gt;
			&lt;img src=&quot;spacer.png&quot; /&gt;&lt;img id=&quot;hoursDownBack&quot; src=&quot;Single/Down/AM/0.png&quot; /&gt;
			&lt;img id=&quot;minutesDownLeftBack&quot; src=&quot;Double/Down/Left/0.png&quot; /&gt;&lt;img id=&quot;minutesDownRightBack&quot; src=&quot;Double/Down/Right/0.png&quot; /&gt;
			&lt;img id=&quot;secondsDownLeftBack&quot; src=&quot;Double/Down/Left/0.png&quot; /&gt;&lt;img id=&quot;secondsDownRightBack&quot; src=&quot;Double/Down/Right/0.png&quot; /&gt;
		&lt;/div&gt;
	&lt;/div&gt;

	&lt;div id=&quot;front&quot;&gt;
		&lt;div id=&quot;upperPart&quot;&gt;
			&lt;img src=&quot;spacer.png&quot; /&gt;&lt;img id=&quot;hoursUp&quot; src=&quot;Single/Up/AM/0.png&quot; /&gt;
			&lt;img id=&quot;minutesUpLeft&quot; src=&quot;Double/Up/Left/0.png&quot; /&gt;&lt;img id=&quot;minutesUpRight&quot; src=&quot;Double/Up/Right/0.png&quot;/&gt;
			&lt;img id=&quot;secondsUpLeft&quot; src=&quot;Double/Up/Left/0.png&quot; /&gt;&lt;img id=&quot;secondsUpRight&quot; src=&quot;Double/Up/Right/0.png&quot;/&gt;
		&lt;/div&gt;
		&lt;div id=&quot;lowerPart&quot;&gt;
			&lt;img src=&quot;spacer.png&quot; /&gt;&lt;img id=&quot;hoursDown&quot; src=&quot;Single/Down/AM/0.png&quot;/&gt;
			&lt;img id=&quot;minutesDownLeft&quot; src=&quot;Double/Down/Left/0.png&quot;/&gt;&lt;img id=&quot;minutesDownRight&quot; src=&quot;Double/Down/Right/0.png&quot; /&gt;
			&lt;img id=&quot;secondsDownLeft&quot; src=&quot;Double/Down/Left/0.png&quot;  /&gt;&lt;img id=&quot;secondsDownRight&quot; src=&quot;Double/Down/Right/0.png&quot;  /&gt;
		&lt;/div&gt;
	&lt;/div&gt;
&lt;/div&gt;

&lt;/body&gt;
&lt;script src=&quot;mootools.js&quot; type=&quot;text/javascript&quot;&gt;&lt;/script&gt;
&lt;script src=&quot;animate.js&quot; type=&quot;text/javascript&quot;&gt;&lt;/script&gt;
&lt;/html&gt;
</pre>
<h3>Step 4: CSS</h3>
<p>The main thing we have to do now is to overlap the &#8220;front&#8221; and &#8220;back&#8221; divs. First we position the main wrapper where we need it and then give the same absolute position to both containers.</p>
<pre name="code" class="css">
#wrapper{
	position:absolute;
	top: 100px;
	left:400px;
}

#front, #back{
	position:absolute;
	top:0px;
}
</pre>
<p>Now we need to vertically align the upper part to the bottom and the lower part to the top, so that the pads would look like they&#8217;re anchored to the middle of the clock. I added the height and visibility properties for the front parts because we need them for the animation later on.</p>
<pre name="code" class="css">
#upperPart, #upperPartBack{
	vertical-align:bottom;
}

#lowerPart, #lowerPartBack{
	vertical-align:top;
}

#upperPart img{
	position:relative;
	height:63px;
	vertical-align:bottom;
	visibility:visible;
}

#lowerPart img{
	position:relative;
	height:63px;
	vertical-align:top;
	visibility:visible;
}

#lowerPartBack img{
	position:relative;
	vertical-align:top;
}

#upperPartBack img{
	position:relative;
	vertical-align:bottom;
}
</pre>
<p>Finally all we have to do is to constrain the width of the pads because we want to play around only with their height. By default, if you change one of them, the hole image will be scaled.</p>
<pre name="code" class="css">
#hoursUp, #hoursDown, #hoursUpBack, #hoursDownBack{
	width:126px;
}

#minutesUpLeft, #minutesUpRight, #minutesDownLeft, #minutesDownRight,
#minutesUpLeftBack, #minutesUpRightBack, #minutesDownLeftBack, #minutesDownRightBack,
#secondsUpLeft, #secondsUpRight, #secondsDownLeft, #secondsDownRight,
#secondsUpLeftBack, #secondsUpRightBack, #secondsDownLeftBack, #secondsDownRightBack{
	width:63px;
}
</pre>
<p> Here it is all put together: </p>
<pre name="code" class="css">
body{
	background:#000;
}

#wrapper{
	position:absolute;
	top: 100px;
	left:400px;
}

#front, #back{
	position:absolute;
	top:0px;
}

#upperPart, #upperPartBack{
	vertical-align:bottom;
}

#lowerPart, #lowerPartBack{
	vertical-align:top;
}

#upperPart img{
	position:relative;
	height:63px;
	vertical-align:bottom;
	visibility:visible;
}

#lowerPart img{
	position:relative;
	height:63px;
	vertical-align:top;
	visibility:visible;
}

#lowerPartBack img{
	position:relative;
	vertical-align:top;
}

#upperPartBack img{
	position:relative;
	vertical-align:bottom;
}

#hoursUp, #hoursDown, #hoursUpBack, #hoursDownBack{
	width:126px;
}

#minutesUpLeft, #minutesUpRight, #minutesDownLeft, #minutesDownRight,
#minutesUpLeftBack, #minutesUpRightBack, #minutesDownLeftBack, #minutesDownRightBack,
#secondsUpLeft, #secondsUpRight, #secondsDownLeft, #secondsDownRight,
#secondsUpLeftBack, #secondsUpRightBack, #secondsDownLeftBack, #secondsDownRightBack{
	width:63px;
}
</pre>
<h3>Step 5: Creating the Animation</h3>
<p>First of all we need some variables to store the time that is shown on the pads. Note: h = hours, m1 = the left minute digit, m2 = the right minute digit, s1 = the left second digit, s2 = the right second digit.</p>
<pre name="code" class="js">
	var h_current = -1;
	var m1_current = -1;
	var m2_current = -1;
	var s1_current = -1;
	var s2_current= -1;
</pre>
<p>Now we create a function that will run every second and update our clock. First we get the current time and determine the time of day, AM or PM.</p>
<pre name="code" class="js">
function retroClock(){

       now = new Date();
       h = now.getHours();
       m1 = now.getMinutes() / 10;
       m2 = now.getMinutes() % 10;
       s1 = now.getSeconds() / 10;
       s2 = now.getSeconds() % 10;
       if(h &lt; 12)
          ap = &quot;AM&quot;;
       else{
          if( h == 12 )
              ap = &quot;PM&quot;;
          else{
              ap = &quot;PM&quot;;
              h -= 12; }
       }
</pre>
<p>Then we compare it to the time shown on the pads and change which group is different. It uses a function called &#8220;flip&#8221; that I will describe in a minute.</p>
<pre name="code" class="js">
       if( h != h_current){
          flip(&#039;hoursUp&#039;, &#039;hoursDown&#039;, h, &#039;Single/Up/&#039;+ap+&#039;/&#039;, &#039;Single/Down/&#039;+ap+&#039;/&#039;);
          h_current = h;
      }

      if( m2 != m2_current){
          flip(&#039;minutesUpRight&#039;, &#039;minutesDownRight&#039;, m2, &#039;Double/Up/Right/&#039;, &#039;Double/Down/Right/&#039;);
          m2_current = m2;

          flip(&#039;minutesUpLeft&#039;, &#039;minutesDownLeft&#039;, m1, &#039;Double/Up/Left/&#039;, &#039;Double/Down/Left/&#039;);
          m1_current = m1;
      }

       if (s2 != s2_current){
          flip(&#039;secondsUpRight&#039;, &#039;secondsDownRight&#039;, s2, &#039;Double/Up/Right/&#039;, &#039;Double/Down/Right/&#039;);
          s2_current = s2;

          flip(&#039;secondsUpLeft&#039;, &#039;secondsDownLeft&#039;, s1, &#039;Double/Up/Left/&#039;, &#039;Double/Down/Left/&#039;);
          s1_current = s1;
      }
}//end retroClock
</pre>
<p>Now, the flip function. It has a few parameters: upperId, lowerId = the ids of the upper and lower pads that will flip; changeNumber = the new value that will be shown; pathUpper, pathLower = the paths to the source files for the new value. The animation is composed of the following steps: <br />
  The front upper pad takes the value of the back one and it&#8217;s made visible, overlaing it, while the lower one is also made visible but it&#8217;s height is changed to 0px.</p>
<pre name="code" class="js">
function flip (upperId, lowerId, changeNumber, pathUpper, pathLower)
{
    var upperBackId = upperId+&quot;Back&quot;;
    $(upperId).src = $(upperBackId).src;
    $(upperId).setStyle(&quot;height&quot;, &quot;63px&quot;);
    $(upperId).setStyle(&quot;visibility&quot;, &quot;visible&quot;);

    $(lowerId).setStyle(&quot;height&quot;, &quot;0px&quot;);
    $(lowerId).setStyle(&quot;visibility&quot;, &quot;visible&quot;);
</pre>
<p>Now we change the back upper and front lower pad to the new value.</p>
<pre name="code" class="js">
	$(upperBackId).src = pathUpper+parseInt(changeNumber)+&quot;.png&quot;;
   $(lowerId).src = pathLower+parseInt(changeNumber)+&quot;.png&quot;;
</pre>
<p>Having this setup we can start the actual animation. As I mentioned earlier it consists of reducing the height of the front upper part to 0%, 0px, and increasing the height of the front lower part to 100%, 63px in this case. After the animation is complete, the back lower pad takes the new value and the front pads are make hidden.</p>
<pre name="code" class="js">
    var flipUpper = new Fx.Tween(upperId, {duration: 200, transition: Fx.Transitions.Sine.easeInOut});
    flipUpper.addEvents({
        &#039;complete&#039;: function(){
            var flipLower = new Fx.Tween(lowerId, {duration: 200, transition: Fx.Transitions.Sine.easeInOut});
                flipLower.addEvents({
                    &#039;complete&#039;: function(){
                        lowerBackId = lowerId+&quot;Back&quot;;
                        $(lowerBackId).src = $(lowerId).src;
                        $(lowerId).setStyle(&quot;visibility&quot;, &quot;hidden&quot;);
                        $(upperId).setStyle(&quot;visibility&quot;, &quot;hidden&quot;);
                    }				});
                flipLower.start(&#039;height&#039;, 64);

        }
                        });
    flipUpper.start(&#039;height&#039;, 0);
}//end flip
</pre>
<p>The final thing to do is to make our main function run every second. </p>
<pre name="code" class="js">
	setInterval(&#039;retroClock()&#039;, 1000);;
</pre>
<p>Here it is all put together.</p>
<pre name="code" class="js">
var h_current = -1;
var m1_current = -1;
var m2_current = -1;
var s1_current = -1;
var s2_current= -1;

function flip (upperId, lowerId, changeNumber, pathUpper, pathLower)
{
    var upperBackId = upperId+&quot;Back&quot;;
    $(upperId).src = $(upperBackId).src;
    $(upperId).setStyle(&quot;height&quot;, &quot;63px&quot;);
    $(upperId).setStyle(&quot;visibility&quot;, &quot;visible&quot;);

    $(lowerId).setStyle(&quot;height&quot;, &quot;0px&quot;);
    $(lowerId).setStyle(&quot;visibility&quot;, &quot;visible&quot;);

	$(upperBackId).src = pathUpper+parseInt(changeNumber)+&quot;.png&quot;;
    $(lowerId).src = pathLower+parseInt(changeNumber)+&quot;.png&quot;;

    var flipUpper = new Fx.Tween(upperId, {duration: 200, transition: Fx.Transitions.Sine.easeInOut});
    flipUpper.addEvents({
        &#039;complete&#039;: function(){
            var flipLower = new Fx.Tween(lowerId, {duration: 200, transition: Fx.Transitions.Sine.easeInOut});
                flipLower.addEvents({
                    &#039;complete&#039;: function(){
                        lowerBackId = lowerId+&quot;Back&quot;;
                        $(lowerBackId).src = $(lowerId).src;
                        $(lowerId).setStyle(&quot;visibility&quot;, &quot;hidden&quot;);
                        $(upperId).setStyle(&quot;visibility&quot;, &quot;hidden&quot;);
                    }				});
                flipLower.start(&#039;height&#039;, 64);

        }
                        });
    flipUpper.start(&#039;height&#039;, 0);
}//end flip

function retroClock(){

     now = new Date();
     h = now.getHours();
     m1 = now.getMinutes() / 10;
     m2 = now.getMinutes() % 10;
     s1 = now.getSeconds() / 10;
     s2 = now.getSeconds() % 10;
     if(h &lt; 12)
        ap = &quot;AM&quot;;
     else{
        if( h == 12 )
            ap = &quot;PM&quot;;
        else{
            ap = &quot;PM&quot;;
            h -= 12; }
     }

     if( h != h_current){
        flip(&#039;hoursUp&#039;, &#039;hoursDown&#039;, h, &#039;Single/Up/&#039;+ap+&#039;/&#039;, &#039;Single/Down/&#039;+ap+&#039;/&#039;);
        h_current = h;
    }

    if( m2 != m2_current){
        flip(&#039;minutesUpRight&#039;, &#039;minutesDownRight&#039;, m2, &#039;Double/Up/Right/&#039;, &#039;Double/Down/Right/&#039;);
        m2_current = m2;

        flip(&#039;minutesUpLeft&#039;, &#039;minutesDownLeft&#039;, m1, &#039;Double/Up/Left/&#039;, &#039;Double/Down/Left/&#039;);
        m1_current = m1;
    }

     if (s2 != s2_current){
        flip(&#039;secondsUpRight&#039;, &#039;secondsDownRight&#039;, s2, &#039;Double/Up/Right/&#039;, &#039;Double/Down/Right/&#039;);
        s2_current = s2;

        flip(&#039;secondsUpLeft&#039;, &#039;secondsDownLeft&#039;, s1, &#039;Double/Up/Left/&#039;, &#039;Double/Down/Left/&#039;);
        s1_current = s1;
    }
}//end retroClock

setInterval(&#039;retroClock()&#039;, 1000);
</pre>
<h3>Finished</h3>
<div class="tutorial_image"><img src="http://nettuts.s3.amazonaws.com/470_clock/0.jpg" border="0" /></div>
<p>We are finished! Hope you&#8217;ve enjoyed working on this little project, it has a somewhat complex concept, but in the end it is a really neat gadget for your websites. Please do not hesitate to send any suggestions you may have!
</p>
<ul class="webroundup">
<li>Follow us on <a href="http://www.twitter.com/nettuts">Twitter</a>, or subscribe to the <a href="http://feeds.feedburner.com/nettuts" title="Nettuts+ RSS Feed">Nettuts+ RSS Feed</a> for more daily web development tuts and articles.</li>
</ul>
<p>
<script type="text/javascript"><!--digg_url = "post permalink (not digg url)"; // -->
</script><br />
<script src="http://digg.com/tools/diggthis.js" type="text/javascript"></script></p>
]]></content:encoded>
			<wfw:commentRss>http://net.tutsplus.com/tutorials/html-css-techniques/learn-how-to-create-a-retro-animated-flip-down-clock/feed/</wfw:commentRss>
		<slash:comments>90</slash:comments>
		</item>
		<item>
		<title>How to Create an Image Gallery Powered by Picasa</title>
		<link>http://net.tutsplus.com/tutorials/javascript-ajax/how-to-create-an-image-gallery-powered-by-picasa/</link>
		<comments>http://net.tutsplus.com/tutorials/javascript-ajax/how-to-create-an-image-gallery-powered-by-picasa/#comments</comments>
		<pubDate>Tue, 20 Oct 2009 18:11:48 +0000</pubDate>
		<dc:creator>Mikhail Kozlov</dc:creator>
				<category><![CDATA[JavaScript & AJAX]]></category>
		<category><![CDATA[AJAX]]></category>
		<category><![CDATA[gallery]]></category>
		<category><![CDATA[image gallery]]></category>
		<category><![CDATA[jQuery]]></category>
		<category><![CDATA[picasa]]></category>

		<guid isPermaLink="false">http://net.tutsplus.com/?p=7292</guid>
		<description><![CDATA[<img src="http://nettuts.s3.amazonaws.com/468_picasa/preview.jpg" alt="preview" width="200" height="200"/>]]></description>
			<content:encoded><![CDATA[<p>In this tutorial we are going to create a simple image gallery powered by Google&#8217;s <a href="picasaweb.google.com">Picasa Web Albums</a>. In order to enhance the user&#8217;s experience, we&#8217;ll throw some jQuery into the mix and create a scrollable album carousel.</p>
<p><span id="more-7292"></span></p>
<div class="tutorial_image">
<a href="http://nettuts.s3.amazonaws.com/468_picasa/PicasaWeb.zip"><img src="http://nettuts.com/wp-content/themes/nettuts/site_images/button_src_nm.jpg"></a>
</div>
<div class="tutorial_image">
   <img src="http://nettuts.s3.amazonaws.com/468_picasa/all_done.jpg" alt="Final Product" />
</div>
<h3>Overview</h3>
<p>
	We are going to use PHP&#8217;s SimpleXML extension to sort and access the data inside the XML feed provided by Picasa Web Albums. jQuery will be responsible for the DOM manipulation and AJAX request. We are also going to use the Scrollable library, which is part of <a href="http://flowplayer.org/tools/index.html">jQuery Tools</a> to create the carousel. Next, we&#8217;ll use jQuery&#8217;s <a href="http://plugins.jquery.com/project/mousewheel">MouseWheel</a> plug-in to allow for cross-browser mouse wheel support. Finally, we&#8217;ll use the <a href="http://fancybox.net/">Fancybox</a> plug-in to each image in a &#8220;lightbox.&#8221;
</p>
<h3>What We Need</h3>
<ul>
<li>Picasa Web Album ID (usually the same as your Gmail or Google account ID)</li>
<li>PHP with <a href="http://us.php.net/simplexml" target="_blank">SimpleXML</a> (it is enabled by default with new PHP install)</li>
<li>Latest <a href="http://code.google.com/p/jqueryjs/downloads/detail?name=jquery-1.3.2.min.js" target="_blank">jQuery</a></li>
<li>Recently Discovered <a href="http://flowplayer.org/tools/index.html" target="_blank">jQuery Tools</a> from flowplayer.org</li>
<li><a href="http://fancybox.net/" target="_blank">Fancybox plug-in for jQuery</a></li>
<li><a href="http://www.960.gs" target="_blank">960 Grid CSS</a> (it is not required but I&#8217;m using it in this tutorial)</li>
</ul>
<h3>Getting Started</h3>
<p>
	We&#8217;ll begin by downloading the files and putting them into the same folder. I also combined all of the Fancybox images with jQuery Tools ones, and placed them inside the <i>img</i> folder.
</p>
<div class="tutorial_image"><img src="http://nettuts.s3.amazonaws.com/468_picasa/file_tree.jpg" border="0" /></div>
<h3>PHP files</h3>
<p>For our project, we are going to use following PHP files:</p>
<ul class="bList">
<li><em>index.php</em></li>
<li><em>_ajax.php</em></li>
<li><em>_conf.php</em></li>
</ul>
<ul>
<li><em>index.php</em> will be responsible for displaying albums, images, and sending requests to <em>_ajax.php</em>. </li>
<li><em>_ajax.php</em> will be handling dynamic request and returning formatted thumbnails </li>
<li><em>_conf.php</em>, as you may have guessed, will contain some configuration information that will be used by both files. </li>
</ul>
<h3><em>_code.php</em></h3>
<p>
	This file is very simple and short.
</p>
<pre name="code" class="php">
// First we need to set some defaults
$gTitle=""; // title of your gallary, if empty it will show: "your nickname' Photo Gallary"
$uName= "kozlov.m.a"; // your picasaweb user name
$tSize="72c"; // thumbnail size can be 32, 48, 64, 72, 144, 160. cropt (c) and uncropt (u)
$maxSize="720u"; // max image size can be 200, 288, 320, 400, 512, 576, 640, 720, 800. These images are available as only uncropped(u) sizes.
</pre>
<p>
	Basically, in this file we set the username (Picasa Web Album ID), thumbnail size, and max image size that we are going to show in our gallery.
</p>
<h3><em>index.php</em></h3>
<p>
	This file requires a bit more to make the gallery work. We begin with referencing our configuration file (<em>_conf.php</em>):
</p>
<pre name="code" class="php">
&lt;?php
include './_conf.php'; // getting constants
</pre>
<p>
	Next we need to load the album feed. We are only retrieving publicly available albums, so our request will look something like: &#8220;http://picasaweb.google.com/data/feed/api/user/user_name?kind=album&amp;access=public&#8221;.
</p>
<pre name="code" class="php"><code>
$file = file_get_contents("http://picasaweb.google.com/data/feed/api/user/".$uName."?kind=album&amp;access=public&amp;thumbsize=".$tSize);
</code></pre>
<p>
	<i>file_get_contents</i> will load content from the XML feed into $file variable. As you can see, we used the <i>$uName</i> variable defined in <i>_conf.php</i> to get the right feed. We also passed the additional parameter &#8220;thumbsize;&#8221; so that the returned feed will contain thumbnails of our chosen size.
</p>
<p>
	Now, let&#8217;s convert the contents of the feed into a SimpleXml object and define the namespaces we are going to use:
</p>
<pre name="code" class="php">
$xml = new SimpleXMLElement($file);
$xml-&gt;registerXPathNamespace('gphoto', 'http://schemas.google.com/photos/2007');
$xml-&gt;registerXPathNamespace('media', 'http://search.yahoo.com/mrss/');
</pre>
<p>
	You can find all namespaces used in the API feeds by visiting <a href="http://code.google.com/apis/picasaweb/docs/2.0/reference.html#Elements">http://code.google.com/apis/&#8230;</a>, but we&#8217;ll only be using &#8220;media&#8221; and &#8220;gphoto&#8221; in our tutorial; you do not have to worry about the rest of them.
</p>
<p>
	Next, we&#8217;ll get the web album&#8217;s name in case we did not already set one in <em>__conf.php</em> file:
</p>
<pre name="code" class="php">
if($gTitle == null){ // if empty Gallery title will be "user id's  Photo Gallery"
$nickname = $xml-&gt;xpath('//gphoto:nickname'); // Mikhail
$gTitle =$nickname[0]."'s Photo Gallery";
}
?>
</pre>
<p>
	Finally, it is time for some simple HTML. We&#8217;ll set our header and reference a few CSS files.
</p>
<pre name="code" class="html">
&lt;!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"&gt;
&lt;html&gt;
&lt;head&gt;
&lt;title&gt;&lt;?php echo $gTitle; ?&gt;&lt;/title&gt;
&lt;link rel="stylesheet" href="reset.css" type="text/css" /&gt;
&lt;link rel="stylesheet" href="960.css" type="text/css" /&gt;
&lt;link rel="stylesheet" href="style.css" type="text/css" /&gt;
&lt;link rel="stylesheet" href="fancybox.css" type="text/css" /&gt;
&lt;/head&gt;
&lt;body&gt;
&lt;div class="container_16"&gt;
&lt;div class="grid_16"&gt;
&lt;?php echo "&lt;h1&gt;". $gTitle ."&lt;/h1&gt;";?&gt;
</pre>
<p>
	As you can see, we&#8217;ve set the page title to <i>$gTitle</i> and have added some CSS to make things pretty.
</p>
<h4>Style Files</h4>
<p>
	I do not think that <em>reset.css</em> needs any additional explanation, so let&#8217;s skip over it and take a closer look at the other stylesheet.
</p>
<ul>
<li><em>960.css</em> allows for a more grid-like layout. </li>
<li><em>style.css</em> comes from the provided stylesheet from <a href="http://flowplayer.org/tools/index.html" target="_blank">jQuery Tools</a>. </li>
<li>And <em>fancybox.css</em> is part of the FancyBox plug-in. </li>
</ul>
<blockquote>
<p>Note: Please make sure that you change image path in both <em>fancybox.css</em> and <em>style.css</em>, so all background images point to <em>img</em> folder. </p>
</blockquote>
<div class="tutorial_image"><img src="http://nettuts.s3.amazonaws.com/468_picasa/html_css.jpg" border="0" /></div>
<h4>Album Holder and Navigational Elements</h4>
<p>
  It is time to create our album holder and navigational elements. This is where <a href="http://flowplayer.org/tools/index.html" target="_blank">jQuery Tools</a> is a huge help. For the album navigation, we&#8217;ll be using the Scrollable library. If you visit the <a href="http://flowplayer.org/tools/scrollable.html" target="_blank">Scrollable reference page</a> and take a look at some of the examples, you&#8217;ll see that we&#8217;re using it almost without any modifications.
</p>
<pre name="code" class="html">
&lt;div&gt;
&lt;a id="prev"&gt;&amp;nbsp;&lt;/a&gt; &lt;!-- Prev controll--&gt;
&lt;/div&gt;
&lt;div id="albums"&gt;
&lt;div&gt;
&lt;!-- php code will go here --&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div&gt;
&lt;a id="next"&gt;&amp;nbsp;&lt;/a&gt;&lt;!-- Next controll--&gt;
&lt;/div&gt;
&lt;div&gt;&amp;nbsp;&lt;/div&gt;
&lt;div id="navi"&gt;&lt;/div&gt; &lt;!-- Pagination holder--&gt;
&lt;div&gt;&amp;nbsp;&lt;/div&gt;
</pre>
<p>
	We&#8217;ll also need a holder for the album picture thumbnails, and the album title that will be loaded via AJAX:
</p>
<pre name="code" class="html">
&lt;h2 id="a_title"&gt;&lt;/h3&gt;
&lt;div id="pic_holder"&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
</pre>
<h4>JavaScript</h4>
<p>
	Let&#8217;s finish our page by referencing the JavaScripts we&#8217;ll be using.
</p>
<pre name="code" class="html">
&lt;script type="text/javascript" language="JavaScript" src="http://jqueryjs.googlecode.com/files/jquery-1.3.2.min.js"&gt;&lt;/script&gt;
&lt;script type="text/javascript" language="JavaScript" src="jquery.tools.min.js"&gt;&lt;/script&gt;
&lt;script type="text/javascript" language="JavaScript" src="jquery.easing.1.3.js"&gt;&lt;/script&gt;
&lt;script type="text/javascript" language="JavaScript" src="jquery.fancybox-1.2.1.pack.js"&gt;&lt;/script&gt;
&lt;/body&gt;
&lt;/html&gt;
</pre>
<h4>PHP</h4>
<div class="tutorial_image"><img src="http://nettuts.s3.amazonaws.com/468_picasa/album-php.jpg" border="0" /></div>
<p>
	Now it is time to go through the XML file and sift the album thumbnails out. Place the following PHP code inside the <em>&lt;/div class=&#8221;items&#8221;&gt;</em> element.
</p>
<pre name="code" class="php">
&lt;?php
foreach($xml-&gt;entry as $feed){
$group = $feed-&gt;xpath('./media:group/media:thumbnail');
$a = $group[0]-&gt;attributes(); // we need thumbnail path
$id = $feed-&gt;xpath('./gphoto:id'); // and album id for our thumbnail
echo '&lt;img src="'.$a[0].'" alt="'.$feed-&gt;title.'" title="'.$feed-&gt;title.'" ref="'.$id[0].'" /&gt;';
?>
}
</pre>
<div class="tutorial_image"><img src="http://nettuts.s3.amazonaws.com/468_picasa/php_html_done.jpg" border="0" /></div>
<p>
	Our plan was to load album pictures once visitors click on a specific thumbnail, therefore we have to create some kind of reference to connect the two. For this purpose, we are putting a <i>ref</i> attribute into each album&#8217;s <i>img</i> tag; so it will look something like this when compiled:
</p>
<pre name="code" class="html">
	&lt;img ref="5364767538132778657" title="2009-07-31 - Beach Ocean City, MD" alt="2009-07-31 - Beach Ocean City, MD" src="http://lh4.ggpht.com/_X7imT2xUAEM/SnN7pvTzfqE/AAAAAAAAHmg/DNWeIS7JGzg/s72-c/20090731BeachOceanCityMD.jpg" /&gt;
</pre>
<h4>AJAX</h4>
<p>
	Finally, we&#8217;ll spice it all up with some jQuery. Firstly, we need to initialize the jQuery Tools plug-in with some additional parameters:
</p>
<pre name="code" class="js">
$("div.scrollable").scrollable({
	size: 10, // number of pictures per "page"
	next: '#next', // id of next control element
	prev: '#prev', // id of prev control element
	navi:'#navi' // id of navigation control holder
});
</pre>
<p>The code above will automatically add scrollable controls.</p>
<div class="tutorial_image"><img src="http://nettuts.s3.amazonaws.com/468_picasa/js_php_html_css.jpg" border="0" /></div>
<blockquote>
<p>Note: It is better to set the scrollable size to an odd number. This way, selected images will appear right in the middle. </p>
</blockquote>
<p>
	Next we&#8217;ll create on click event for the album thumbnail:
</p>
<pre name="code" class="js">
$("#albums img").bind("click", function(){
	$("#a_title").text($(this).attr('title'));
	$("#pic_holder").html('&lt;div&gt;&lt;img src="/images/loading.gif" alt="Loading..."&gt;&lt;/div&gt;').load("_ajax.php",{"aID":$(this).attr("ref")},function(){
	$("#pic_holder").find("a").fancybox();
	});
});</pre>
<p>
	Let&#8217;s take close look at what we are doing here. First we define our click event trigger:
</p>
<pre name="code" class="js">
$("#albums img").bind("click", function(){
</pre>
<p>
	We use <i>bind</i> instead of the simple <i>click</i> because we do not want to interrupt the work of the scrollable plug-in that we just initiated above.
</p>
<p>
	Next, we&#8217;ll apply the album title into the <i>h2</i> tag with id &#8220;a_title&#8221; from the title attribute of the anchor tag:
</p>
<pre name="code" class="js">
	$("#a_title").text($(this).attr('title'));
</pre>
<p>
	Finally, we send an AJAX request to <em>_ajax.php</em> and let Fancybox re-index the freshly loaded images:
</p>
<pre name="code" class="js">
$("#pic_holder").html('&lt;div&gt;&lt;img src="/images/loading.gif" alt="Loading..."&gt;&lt;/div&gt;').load("_ajax.php",{"aID":$(this).attr("ref")},function(){
 	$("#pic_holder").find("a").fancybox();
});
</pre>
<p>
	As you probably noticed, we are inserting a &#8220;loading image&#8221; inside &#8220;pic_holder&#8221; before sending the AJAX request.  This will provide the user with some feedback to let them know that their request is currently being processed. Once we receive a response from the server, jQuery will replace the contents of the &#8220;pic_holder&#8221; with data that came from <i>_ajax.php</i>.
</p>
<h3>_ajax.php</h3>
<p>
	Now it is time to serve the contents of the album to our visitors. Our plan is to show thumbnails linked to originals on the Picasa server. Once a thumbnail is clicked, Fancybox will take over and create a lightbox-like image gallery. We&#8217;ll start with the entire contents of the file, and then go over each line:
</p>
<pre name="code" class="php">
&lt;?php
	include './_conf.php'; // getting constants
	if(isset($_POST['aID'])){
		$aID = $_POST['aID']; // let's put album id here so it is easie to use later
		$file = file_get_contents('http://picasaweb.google.com/data/feed/api/user/'.$uName.'/albumid/'.$aID.'?kind=photo&amp;access=public&amp;thumbsize=72c&amp;imgmax='.$maxSize); // get the contents of the album
		$xml = new SimpleXMLElement($file); // convert feed into SimpleXML object
		$xml-&gt;registerXPathNamespace('media', 'http://search.yahoo.com/mrss/'); // define namespace media
		foreach($xml-&gt;entry as $feed){ // go over the pictures
		$group = $feed-&gt;xpath('./media:group/media:thumbnail'); // let's find thumbnail tag
		$description = $feed-&gt;xpath('./media:group/media:description'); // file name appended by image captioning
		if(str_word_count($description[0]) &gt; 0){ // if picture has description, we'll use it as title
			$description = $feed-&gt;title. ": ". $description[0];
		}else{
			$description =$feed-&gt;title; // if not will use file name as title
		}
		$a = $group[0]-&gt;attributes(); // now we need to get attributes of thumbnail tag, so we can extract the thumb link
		$b = $feed-&gt;content-&gt;attributes(); // now we convert "content" attributes into array
		echo '&lt;a rel="'.$aID.'" href="'.$b['src'].'" title="'.$description.'"&gt;&lt;img src="'.$a['url'].'" alt="'.$feed-&gt;title.'" width="'.$a['width'].'" height="'.$a['height'].'"/&gt;&lt;/a&gt;';
		}
	}else{
		echo 'Error! Please provide album id.';
	}
?>
</pre>
<p>
	First, we are going to reference our configuration file, so we can have access to the constant parameters: Picasa ID and thumbnail size.
</p>
<pre name="code" class="php">
include './_conf.php'; // getting constants
</pre>
<p>
	Then we&#8217;ll check if the album ID was sent via POST request:
</p>
<pre name="code" class="php">
if(isset($_POST['aID'])){
</pre>
<p>
	If we did not find an album ID, we&#8217;re simply going to print an error message:
</p>
<pre name="code" class="php">
}else{
   echo 'Error! Please provide album ID.';
}
</pre>
<p>
	If <em>_ajax.php</em> received the album ID, we&#8217;ll get an XML feed and start working on it, so let&#8217;s create a link to the correct XML feed:
</p>
<pre name="code" class="php">
 $aID = $_POST['aID']; // let's put the album id here so it is easier to use later
 $file = file_get_contents('http://picasaweb.google.com/data/feed/api/user/'.$uName.'/albumid/'.$aID.'?kind=photo&amp;access=public&amp;thumbsize=72c&amp;imgmax='.$maxSize); // get the contents of the album
</pre>
<p>
	As you can see, we use the album ID that came via the POST request as well as constants from <i>_conf.php</i> file. Again, we are using <i>file_get_contents</i> to load the XML feed and store it in the <i>$file</i> variable. Next we convert it to a SimpleXMLElement object cycle through each <i>entry</i> nodes that contain information about each picture. To do so, we&#8217;ll use a simple foreach() loop. </p>
<pre name="code" class="php">
foreach($xml-&gt;entry as $feed){ // go over the pictures
</pre>
<p>
	Next, we are ready to extract data needed for our link and thumbnail. I&#8217;ve commented every line and hopefully it is enough to understand what is going on:
</p>
<pre name="code" class="php">
$group = $feed-&gt;xpath('./media:group/media:thumbnail'); // let's find the thumbnail tag
$description = $feed-&gt;xpath('./media:group/media:description');  // let's find the description tag
if(str_word_count($description[0]) &gt; 0){ // if the picture has description, we'll use it as the title
	$description = $feed-&gt;title. ": ". $description[0]; // file name appended by image captioning
}else{
	$description =$feed-&gt;title; // if not, will use file name as title
}
$a = $group[0]-&gt;attributes(); // now we need to get attributes of thumbnail tag, so we can extract the thumb link
$b = $feed-&gt;content-&gt;attributes(); // now we convert "content" attributes into array
</pre>
<p>
	Finally, we are putting it all into HTML context. We&#8217;ll echo a link to the original image and thumbnail image:
</p>
<pre name="code" class="php">
echo '&lt;a rel="'.$aID.'" href="'.$b['src'].'" title="'.$description.'"&gt;&lt;img src="'.$a['url'].'" alt="'.$feed-&gt;title.'" width="'.$a['width'].'" height="'.$a['height'].'"/&gt;&lt;/a&gt;';
</pre>
<div class="tutorial_image"><img src="http://nettuts.s3.amazonaws.com/468_picasa/all_done.jpg" border="0" /></div>
<p>
	To force Fancybox to organize all of the images into a gallery, we are adding the <em>rel</em> attribute to each link. You can simply put same number or string as value, but I&#8217;m going to use the album ID.
</p>
<h3>Styling</h3>
<p>
	As I mentioned before, most of the styling was taken straight from examples at the <a href="http://flowplayer.org/tools/index.html" target="_blank">jQuery Tools</a> website. All you must do here is simply adjust the height and width to suit the design of your website.
</p>
<h3>Mouse Wheel Scroll</h3>
<p>
	Mouse Wheel Scroll is another beauty that you can easily use. As some may have noticed, we never initiated this plug-in; yet, if you hover over the album carousel and try to scroll with your mouse wheel, it will work thanks to jQuery Tools.
</p>
<h3>Conclusion</h3>
<p>
We&#8217;ve learned how to combine PHP&#8217;s SimpleXML extension with a handful of plugins and Picasa to create a beautiful and dynamic image gallery. I hope you enjoyed and learned from it!</p>
<ul class="webroundup">
<li>Follow us on <a href="http://www.twitter.com/nettuts">Twitter</a>, or subscribe to the <a href="http://feeds.feedburner.com/nettuts" title="Nettuts+ RSS Feed">Nettuts+ RSS Feed</a> for more daily web development tuts and articles.</li>
</ul>
<p>
<script type="text/javascript"><!--digg_url = "post permalink (not digg url)"; // -->
</script><br />
<script src="http://digg.com/tools/diggthis.js" type="text/javascript"></script></p>
]]></content:encoded>
			<wfw:commentRss>http://net.tutsplus.com/tutorials/javascript-ajax/how-to-create-an-image-gallery-powered-by-picasa/feed/</wfw:commentRss>
		<slash:comments>38</slash:comments>
		</item>
		<item>
		<title>Drag to Share</title>
		<link>http://net.tutsplus.com/tutorials/javascript-ajax/drag-to-share/</link>
		<comments>http://net.tutsplus.com/tutorials/javascript-ajax/drag-to-share/#comments</comments>
		<pubDate>Mon, 19 Oct 2009 17:35:06 +0000</pubDate>
		<dc:creator>Dan Wellman</dc:creator>
				<category><![CDATA[JavaScript & AJAX]]></category>
		<category><![CDATA[drag]]></category>
		<category><![CDATA[jQuery]]></category>
		<category><![CDATA[jQuery ui]]></category>

		<guid isPermaLink="false">http://net.tutsplus.com/?p=7274</guid>
		<description><![CDATA[<img src="http://nettuts.s3.amazonaws.com/467_dragtoShare/source/rover.png" alt="Drag to Share" />]]></description>
			<content:encoded><![CDATA[<p>
We’ve all seen the brilliant functionality on Mashable where news stories and interesting articles can be shared to social networking sites; the functionality is driven by the images accompanying the articles; you click and hold on an image and can then drag it into a toolbar to share it. It’s brilliant and intuitive, and in this article I’m going to show you how we can replicate this behavior with jQuery and jQuery UI.
</p>
<p><span id="more-7274"></span></p>
<div class="tutorial_image">
<a href="http://nettuts.s3.amazonaws.com/467_dragtoShare/source.zip"><img src="http://nettuts.com/wp-content/themes/nettuts/site_images/button_src_nm.jpg"></a><br />
<a href="http://nettuts.s3.amazonaws.com/467_dragtoShare/source/dragToShare.html"><img src="http://nettuts.com/wp-content/themes/nettuts/site_images/button_demo_nm.jpg"></a>
</div>
<p>The following screenshot shows what we’ll have at the end of the tutorial: </p>
<div class="tutorial_image">
   <img src="http://nettuts.s3.amazonaws.com/467_dragtoShare/images/1.png" alt="Final Product" style="width: 600px;" />
</div>
<h3>Getting Started</h3>
<p>
The latest version of jQuery comes with jQuery UI and in this example we only need the core, draggable and droppable components, so make sure only these are selected in the download builder. Once the jQuery UI archive has been downloaded, unpack the js folder from the archive (we don’t need the development bundle or CSS framework in this example) in a working folder.
</p>
<p>
Now let’s create a basic page, with some text and an image on it, to showcase the behaviour; create the following new page in your code editor:
</p>
<pre name="code" class="html">
&lt;!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
&lt;html>
  &lt;head>
    &lt;meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    &lt;title>Drag to Share Example&lt;/title>
    &lt;link rel="stylesheet" type="text/css" href="dragToShare.css">
  &lt;/head>
  &lt;body>
    &lt;div id="content">
      &lt;p>Lorem ipsum dolor...&lt;/p>
      &lt;img src="rover.png" alt="Mars Rover">
      &lt;p>Lorem ipsum dolor...&lt;/p>
    &lt;/div>
    &lt;script type="text/javascript" src="js/jquery-1.3.2.min.js">&lt;/script>
    &lt;script type="text/javascript" src="js/jquery-ui-1.7.2.custom.min.js">&lt;/script>
  &lt;/body>
&lt;/html>
</pre>
<p>
Save this as dragToShare.html in the folder with the js folder in it. Here we’ve added our layout/example text and an image, both within a container. We’re linking to the jQuery and jQuery UI source files at the bottom of the &lt;body> and a custom style sheet in the &lt;head>.  We don’t need many styles at this point as there isn’t much on the page to actually style, but let’s add it next anyway with some basic styles for the page elements in it; in a new file in your code editor add the following:
</p>
<pre name="code" class="css">
#content { width:440px; }
#content img { float:right; margin-left:20px; }
</pre>
<p>
Save this tiny file as dragToShare.css in the same folder as our HTML page. Don’t worry, we’ll be adding some more styles to the style sheet very shortly. Our example page should look like this at this point:
</p>
<div class="tutorial_image">
   <img src="http://nettuts.s3.amazonaws.com/467_dragtoShare/images/2.png" alt="Example 2" />
</div>
<h3>
Making the Image Draggable<br />
</h3>
<p>
We need to make the image draggable, which we can do with jQuery UI, add the following &lt;script> element after the others:
</p>
<pre name="code" class="js">
&lt;script type="text/javascript">
  $(function() {

    var images = $("#content img"),
      title = $("title").text() || document.title;

    //make images draggable
    images.draggable();
  });
&lt;/script>
</pre>
<p>
That’s all we need to do! We just cache the selector for the element(s) that we’d like to make draggable, and call the draggable() method on the resulting collection of elements. Now by clicking and holding the mouse button, the image in our example can be dragged around the page. The image will be made draggable as soon as the document is loaded as our code is wrapped in the $(function(){}) shortcut.
</p>
<p>
As well as caching the selector that returns our images, we’re also caching a selector that stores the title of the page. IE returns an empty string when using jQuery to retrieve the page title so we revert to document.title in this case.
</p>
<p>We still have a lot to do before we’re done though; what we need to do first is to let the visitor know that dragging the image does something. Firstly we can use a little CSS to set the ‘move’ mouse pointer when we hover over the image; add the following line to the end of dragToShare.css:
</p>
<pre name="code" class="css">
.ui-draggable { cursor:move; }
</pre>
<p>
We’re targeting the class .ui-draggable which is added by jQuery UI with this style so that the image will only inherit the move cursor if the image is made draggable, which won’t happen if JavaScript is switched off or otherwise unavailable. Using the class name instead of the :hover pseudo class is also much better for cross-browser compatibility.
</p>
<h3>
Information Overlay<br />
</h3>
<div class="tutorial_image">
   <img src="http://nettuts.s3.amazonaws.com/467_dragtoShare/images/3.png" alt="Example 3" />
</div>
<p>
To really make it obvious that dragging the image does something, we can also add a tooltip to explicitly tell the visitor what to do; after the draggable() method add the following new code:
</p>
<pre name="code" class="js">
var createTip = function(e) {
  //create tool tip if it doesn't exist
  ($("#tip").length === 0) ? $("&lt;div>").html("&lt;span>Drag this image to share the page&lt;\/span>&lt;span class='arrow'>&lt;\/span>").attr("id", "tip").css({ left:e.pageX + 30, top:e.pageY - 16 }).appendTo("body").fadeIn(2000) : null;
};

images.bind("mouseenter", createTip);

images.mousemove(function(e) {

  //move tooltip
  $("#tip").css({ left:e.pageX + 30, top:e.pageY - 16 });
});

images.mouseleave(function() {

  //remove tooltip
  $("#tip").remove();
});
</pre>
<p>
We’ve basically added three new event handlers to our code; the first event handler is the createTip function, which is defined as a variable and passed to jQuery’s bind() method along with the string mouseenter specifying the event. The next two functions are anonymous and are passed inline to jQuery’s mousemove() and mouseleave() helper methods.
</p>
<p>
In the createTip function we first check whether the tooltip already exists by seeing if a selector for it has a length of 0. If it does (have a length of 0) we know it doesn’t exist and can then create it. We set the innerHTML of the tooltip so that it features a span containing the message to the visitor, and a second empty span which we’ll use for a little decoration when we add the additional CSS in a moment.
</p>
<p>
We give the tooltip an id so that we can select it efficiently later on and set its CSS left and top properties using the pageX and pageY properties from the event object (e) which is passed to our function automatically. We then append the tooltip to the body of the page and fade it in slowly. To avoid HTML errors, we need to escape the forward-slashes in the raw HTML we add to the tooltip.
</p>
<p>
The mousemove function is used to make the tooltip track with the pointer, so when the pointer moves, the tooltip moves with it. We use the css method again as well as the pageX and pageY properties. Finally, the mouseleave function simply removes the tooltip from the page.
</p>
<h3>
Styling the Tooltip<br />
</h3>
<div class="tutorial_image">
   <img src="http://nettuts.s3.amazonaws.com/467_dragtoShare/images/4.png" alt="Example 4" />
</div>
<p>
Now we can add some CSS for our tooltip; in the interests of progressive enhancement we’ll use the sexy CSS3 rgba style to make out tooltip semi-transparent in capable browsers; at the bottom of dragToShare.css add the following new selectors and rules:
</p>
<pre name="code" class="css">
#tip {
  position:absolute; display:none; height:25px; padding:9px 9px 0px;
  color:#fff; font-family:Verdana, Arial, Helvetica, sans-serif;
  font-size:11px; font-weight:bold; border-radius:4px;
  -moz-border-radius:4px; -webkit-border-radius:4px;
  background:#000; background:rgba(0,0,0,.5);
}
#tip .arrow {
  width:0; height:0; line-height:0; border-right:8px solid #000;
  border-right:8px solid rgba(0,0,0,.5); border-top:8px solid transparent;
  border-bottom:8px solid transparent; position:absolute; left:-8px;
  top:9px;
}
</pre>
<p>
That’s all we need. Most of the styles are pretty basic but we use the border-radius styles to give the tooltip rounded corners in gecko and webkit browsers, and as I mentioned before we use rgba to make the tooltip semi-transparent. This is a great effect and while it’s only supported in a few of the common browsers, it’s much more efficient than using an alpha-transparent PNG.
</p>
<p>
The empty span that we added to the tooltip is styled so that it looks like a speech-bubble arrow pointing to the mouse pointer. This is created using the CSS-shapes technique and as it’s not CSS3 it’s supported in most browsers. It’s even supported in IE6, although the border transparency that we give it isn’t supported. We could fix this easily enough if we really wanted to, but for the purposes of this tutorial I’m not going to deviate to this topic.
</p>
<p>
Note that we also use rgba for the border-color of our span so that it blends in with the rest of the tooltip. Now, IE (any version) is not going to support these rgba styles, but as we have provided normal colors before the rgba declarations, in both the tip and the span, the tooltip will just appear solid black in IE. Here’s how our tooltip will appear at its best, beautiful isn’t it?
</p>
<div class="tutorial_image">
   <img src="http://nettuts.s3.amazonaws.com/467_dragtoShare/images/5.png" alt="Example 5" />
</div>
<h3>
Adding the Drop Targets<br />
</h3>
<p>
Ok, so our visitors now know that they can drag the image somewhere in order to share the page, but where do they drag it to? And where can they share it? We now need to react to the image being dragged and show the drop targets, which will consist of a series of links to social networking sites. We’ve several things we need to do here; we need to add an overlay to the page and create the drop targets first of all.
</p>
<p>
We could create the drop targets entirely from scratch, on the fly, with jQuery like we did with the tooltip, but out in the wild this would probably result in an unacceptable delay for some visitors. We can minimise this by adding the underlying mark-up for the drop targets to the page, and just showing it when we need to. Directly before the &lt;script> elements at the bottom of the page, add the following code:
</p>
<pre name="code" class="html">
<ul id="targets">
<li id="twitter"><a href="http://twitter.com"><!-- --></a></li>
<li id="delicious"><a href="http://delicious.com"><!-- --></a></li>
<li id="facebook"><a href="http://www.facebook.com"><!-- --></a></li>
</ul>
</pre>
<p>
We use a simple unordered list as the container for the drop targets where each item corresponds to a single target; I’ve included the social networking sites that I have accounts for, feel free to add more if you wish. Each list item contains a link with its href set to the home page of the social networking site that it represents. We’ll need to modify these URLs later in our script, and while more information could be provided in these links, I thought it cleaner to just provide the basic URL in the mark-up.
</p>
<p>
We need to style these now as well; add the following new styles to the bottom of our style sheet:
</p>
<pre name="code" class="css">
#targets {
  display:none; list-style-type:none; position:absolute; top:10px;
  z-index:99999;
}
#targets li {
  float:left; margin-right:20px; display:block; width:60px; height:60px;
  background:url(iconSprite.png) no-repeat 0 0; position:relative;
}
#targets li#delicious { background-position:0 -60px; }
#targets li#facebook { background-position:0 -120px; }
</pre>
<p>
The outer list container is initially hidden from view so that we can show it when a drag begins. We disable the default icon for list items (a small circle) and position it absolutely at the top of the page. As we want the icons to be visible above the overlay, we set a high z-index on it.
</p>
<p>
The list items are floated so that they stack up next to each other horizontally and are spaced out with a little margin. The images are set on the list items so an appropriate size is set for them. We’re using a sprite file for the images so we need to set the background position of the delicious and Facebook icons.
</p>
<p>
Note: the icons used in this example came from the Social.me icon pack by jwloh and are available from <a href="http://jwloh.deviantart.com/art/Social-me-90694011">here</a>. They aren’t visible yet, but with the CSS we just added they should look something like this:
</p>
<div class="tutorial_image">
   <img src="http://nettuts.s3.amazonaws.com/467_dragtoShare/images/6.png" alt="Example 6" />
</div>
<h3>
Wiring up the Drag Behavior<br />
</h3>
<p>
At this point, we’ve got out drop targets in place ready to be shown so we now need to set some of draggable’s configuration options in order to add the overlay and show the drop targets when a drag begins. We can also create a helper element that will be dragged instead of the underlying &lt;img>. Change the draggable() method so that it appears as follows:
</p>
<pre name="code" class="js">
//make images draggable
images.draggable({
  //create draggable helper
  helper: function() {
    return $("&lt;div>").attr("id", "helper").html("&lt;span>" + title + "&lt;/span>&lt;img id='thumb' src='" + $(this).attr("src") + "'>").appendTo("body");
  },
  cursor: "pointer",
  cursorAt: { left: -10, top: 20 },
  zIndex: 99999,
  //show overlay and targets
  start: function() {
    $("&lt;div>").attr("id", "overlay").css("opacity", 0.7).appendTo("body");
	$("#tip").remove();
	$(this).unbind("mouseenter");
	$("#targets").css("left", ($("body").width() / 2) - $("#targets").width() / 2).slideDown();
  },
  //remove targets and overlay
  stop: function() {
    $("#targets").slideUp();
    $(".share", "#targets").remove();
    $("#overlay").remove();
    $(this).bind("mouseenter", createTip);
  }
});
</pre>
<p>
We’ve added an object literal as an argument to the draggable() method containing a series of configuration options; let’s look at each option in detail: </p>
<h4>helper</h4>
<p>
We supply an anonymous function as the value of the helper option; the function must return an element, so we create a new div element, give it an id and insert a string of raw HTML. The HTML we insert creates a new span element containing the title of the page. We also create a new image. The image will act as a thumbnail; again we give it an id for styling purposes and set its src attribute to the src of the original image.
</p>
<h4>cursor</h4>
<p>
We set the cursor option to pointer so that an action pointer is shown while the drag is in progress.
</p>
<h4>
cursorAt<br />
</h4>
<p>
We use another object literal with the cursorAt option to position where on the drag helper the icon appears. We set the left and top properties of the object to the pixel values. The values we supply set the cursor so that it appears -10px to the left of the helper, and 20 pixels into it.
</p>
<h4>
zIndex<br />
</h4>
<p>
We set the z-index of the helper element using the zIndex option, which sets the style directly on the element as an inline style. This forces the helper above the overlay, and is required because the overlay is inserted after the helper.
</p>
<h4>
start<br />
</h4>
<p>
This option is one of the draggable component’s built-in event handlers; whenever a drag interaction starts the function we supply as a value to this option is executed. Within this function we create the overlay and append it to the page, remove the tooltip and stop the current image displaying it again, and then position the targets in the center of the viewport before showing them with a nice slideDown animation.
</p>
<h4>
stop<br />
</h4>
<p>
The stop option is another of draggable’s built-in event handlers and is called when the drag stops. All we do here is tidy up, removing the overlay and any text that has been added, sliding up the targets, and rebinding the createTip function to the mouseenter event.
</p>
<p>
So with these options configured, when we begin dragging the image several things will happen; first of all the overlay will be displayed which will grey out the rest of the page. We also remove the tooltip and prevent it from displayed again if the mouse pointer enters the image again. In most browsers this isn’t a problem – the pointer isn’t considered ‘over’ the image because it’s on top of the drag helper. But IE (even version <img src='http://net.tutsplus.com/wp-includes/images/smilies/icon_cool.gif' alt='8)' class='wp-smiley' /> does consider it over the image still and displays both the helper and the tooltip.
</p>
<p>
Our helper element, which will be dragged instead of the original image, will also be created and displayed, showing the page title as a label, and a thumbnail version of the original image. The drop targets will also be shown with a nice animation.
</p>
<p>
At this stage, we need to provide a little CSS for the helper element, thumbnail and the overlay; add the following selectors and rules to the bottom of dragToShare.css:
</p>
<pre name="code" class="css">
#overlay {
  background-color:#000; position:absolute; top:0; left:0; width:100%;
  height:100%; z-index:99997;
}
#helper {
  background-color:#c2c2c2; position:absolute; height:35px;
  padding:15px 70px 0 20px; color:#fff;
  font-family:Verdana, Arial, Helvetica, sans-serif; font-weight:bold;
  font-size:18px; border-radius:8px; -moz-border-radius:8px;
  -webkit-border-radius:8px; border:3px solid #7d7d7d;
}
#thumb {
  width:50px; height:50px; position:absolute; right:0; top:0;
  border-left:3px solid #7d7d7d;
}
</pre>
<p>
For the overlay we set the background color to solid black, but remember we use jQuery to make it transparent. It’s positioned and sized to cover the whole page and has its z-index set to just under that of the drag helper and targets.
</p>
<p>
The helper element has a range of styles set on it to make it presentable. Mostly these are simple everyday styles that don’t warrant discussion, but we do set the border-radius styles here like we did with the tooltip. The height of the helper is fixed, but its width is not, so it will grow or shrink to accommodate all of the alt text from the image that was dragged.
</p>
<p>
The thumbnail version of the original image is sized and positioned at the far right of the helper. Enough right-padding has been given to the helper element to ensure that the text doesn’t run in to the image. When a drag begins, the page should appear like this:
</p>
<div class="tutorial_image">
   <img src="http://nettuts.s3.amazonaws.com/467_dragtoShare/images/7.png" alt="Example 7" />
</div>
<h3>
Making the Targets Droppable<br />
</h3>
<p>
Our final task is to make the target social networking icons to react to having the helper element dropped on to them. We do this using the droppable component of jQuery UI, which we selected when we built our jQuery UI download.
</p>
<p>
Directly after the draggable method (containing the code we just added) add the droppable method:
</p>
<pre name="code" class="js">
//make targets droppable
$("#targets li").droppable({
  tolerance: "pointer",
  //show info when over target
  over: function() {
    $(".share", "#targets").remove();
    $("&lt;span>").addClass("share").text("Share on " + $(this).attr("id")).addClass("active").appendTo($(this)).fadeIn();
  },
  drop: function() {
    var id = $(this).attr("id"),
      currentUrl = window.location.href,
	baseUrl = $(this).find("a").attr("href");

    if (id.indexOf("twitter") != -1) {
      window.location.href = baseUrl + "/home?status=" + title + ": " + currentUrl;
    } else if (id.indexOf("delicious") != -1) {
      window.location.href = baseUrl + "/save?url=" + currentUrl + "&#038;title=" + title;
    } else if (id.indexOf("facebook") != -1) {
      window.location.href = baseUrl + "/sharer.php?u=" + currentUrl + "&#038;t=" + title;
    }
  }
});
</pre>
<p>
Again, we use several different configuration options to tailor the implementation to our needs. The options we use are listed below:
</p>
<h4>tolerance</h4>
<p>
The tolerance option is used to set when the drag helper is considered to be over a drop target. We’ve used pointer here so the mouse pointer itself must be over the drop target.
</p>
<h4>
over<br />
</h4>
<p>
We use the over event callback to execute code whenever the drag helper is over a drop target; in this function we first ensure that the element we’re about to create is removed, this is to hide elements that may have been created in a previous drag. We then create a new span element and set its innerText to a message indicating which social network the icon represents.
</p>
<h4>
drop<br />
</h4>
<p>
The drop event callback function is where we actually perform the sharing of the page on whichever social network the visitor dropped the drag helper on. We get the URL of the current page and the URL for the social network from the href of the link in the list item representing the icon. Each of the social networks used in this example are able to accept information via the URL, so for example with Twitter, we can add the text for a status update to the input field on the visitor’s Twitter page, making it easy for the visitor to share the page title and URL. The information to do this is passed in the URL, so starting with the baseUrl we can build the required URL and then navigate to it with the window.location.href property.
</p>
<p>We need one line of CSS and then we’re done; to style the share message that we append to the page when the drag helper is over a drop target add the following code:
</p>
<pre name="code" class="css">
.share {
  font-weight:bold; position:absolute; font-size:14px;
  font-family:Verdana; margin-left:-38px;
}
</pre>
<p>
We should now find that when we drop the drag helper onto one of the icons, the corresponding page should load with the URL of our page displayed:
</p>
<div class="tutorial_image">
   <img src="http://nettuts.s3.amazonaws.com/467_dragtoShare/images/8.png" alt="Facebook Example" style="width: 600px;" />
</div>
<h3>
Summary<br />
</h3>
<div class="tutorial_image">
   <img src="http://nettuts.s3.amazonaws.com/467_dragtoShare/images/1.png" alt="Final Product" style="width: 600px;" />
</div>
<p>
Our work here is done; we can now deploy the code to our web pages to provide an easy way for our visitors to share our content across their social networks. This method is good because it’s easy to implement consisting entirely of client-side code. We don’t need to worry about authentication or anything like that – the visitor will just be prompted to enter their username and password when the external site loads up.
</p>
<ul class="webroundup">
<li>Follow us on <a href="http://www.twitter.com/nettuts">Twitter</a>, or subscribe to the <a href="http://feeds.feedburner.com/nettuts" title="Nettuts+ RSS Feed">Nettuts+ RSS Feed</a> for more daily web development tuts and articles.</li>
</ul>
<p>
<script type="text/javascript"><!--digg_url = "post permalink (not digg url)"; // -->
</script><br />
<script src="http://digg.com/tools/diggthis.js" type="text/javascript"></script></p>
]]></content:encoded>
			<wfw:commentRss>http://net.tutsplus.com/tutorials/javascript-ajax/drag-to-share/feed/</wfw:commentRss>
		<slash:comments>71</slash:comments>
		</item>
		<item>
		<title>An Introduction to the Raphael JS Library</title>
		<link>http://net.tutsplus.com/tutorials/javascript-ajax/an-introduction-to-the-raphael-js-library/</link>
		<comments>http://net.tutsplus.com/tutorials/javascript-ajax/an-introduction-to-the-raphael-js-library/#comments</comments>
		<pubDate>Wed, 14 Oct 2009 16:26:44 +0000</pubDate>
		<dc:creator>Damian Dawber</dc:creator>
				<category><![CDATA[JavaScript & AJAX]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[js]]></category>
		<category><![CDATA[library]]></category>
		<category><![CDATA[raphael]]></category>

		<guid isPermaLink="false">http://net.tutsplus.com/?p=7186</guid>
		<description><![CDATA[<img src="http://nettuts.s3.amazonaws.com/462_raphael/preview.jpg" alt="An Introduction to the Raphael JS Library" width="200" height="200"/>]]></description>
			<content:encoded><![CDATA[<p><a href="http://raphaeljs.com/">Raphael JS</a> is a lightweight and super-sexy JavaScript framework that allows you to draw vector graphics in your browser! In this tutorial, I will introduce you to some basic drawing functionality, take a look at animation, provide DOM access and finally finish off by creating a cool widget for your site&#8230;</p>
<p><span id="more-7186"></span></p>
<div class="tutorial_image">
<a href="http://nettuts.s3.amazonaws.com/462_raphael/download_files.zip"><img src="http://nettuts.com/wp-content/themes/nettuts/site_images/button_src_nm.jpg"></a>
</div>
<h3>Tutorial Details</h3>
<ul>
<li><b>Framework</b>: Raphael JS</li>
<li><b>Version</b>: 1.0</li>
<li><b>Difficulty:</b> Beginner to Intermediate</li>
<li><b>Estimated Completion Time:</b> 30 minutes</li>
</ul>
<h3>1. Getting Set Up</h3>
<p>Let&#8217;s get started by downloading the Raphael JS framework from <a href="http://raphaeljs.com">here</a>. At the top right of the page, you&#8217;ll see<br />
        compressed and uncompressed copies of Raphael version 1.0. I&#8217;d recommend you grab yourself a copy of the uncompressed source for the time being &#8211; this<br />
        way you can have a peek at the source and see what extra edge you can get on the documentation.</p>
<div class="tutorial_image"><img src="http://nettuts.s3.amazonaws.com/462_raphael/downloadicon.jpg" border="0" /></div>
<p>With that downloaded, let&#8217;s set up a simple HTML document called <i>index.htm</i> and include Raphael in it. We also include <i>our_script.js</i>, which is where<br />
        we&#8217;ll write our own JavaScript, and in the body of the document we create a minimally styled div with ID <i>canvas_container</i>, which will act as a<br />
        container for our drawings.</p>
<pre name="code" class="html">
&lt;html>
    &lt;head>
        &lt;title>Raphael Play&lt;/title>
        &lt;script type="text/javascript" src="path/to/raphael.js">&lt;/script>
        &lt;script type="text/javascript" src="path/to/our_script.js">&lt;/script>
        &lt;style type="text/css">
            #canvas_container {
                width: 500px;
                border: 1px solid #aaa;
            }
        &lt;/style>
    &lt;/head>
    &lt;body>
        &lt;div id="canvas_container">&lt;/div>
    &lt;/body>
&lt;/html>
        </pre>
<p>N.B. <i>The first stable release of version 1.0 was only made available on the 7th October 2009, so it&#8217;s pretty new. It makes one very important change to the way<br />
        you draw paths, so if you&#8217;re using an earlier version of Raphael, make sure you upgrade and check out the documentation on effecting backwards compatibility.</i></p>
<h3>2. Creating our Drawing Canvas</h3>
<p>When we draw with Raphael, we do so <i>onto a canvas</i>. This canvas, which we&#8217;ll reference in a variable called &#8216;paper&#8217;, is created using the<br />
           Raphael() object. We always specify the width and height of the canvas, but have the option of also specifying either a) the absolute position of<br />
           the canvas relative to the viewport, or b) an element &#8216;container&#8217; that the canvas is drawn inside.</p>
<pre name="code" class="js">
var paper = new Raphael(x, y, width, height); //option (a)
var paper = new Raphael(element, width, height); //option (b)
        </pre>
<p>I generally prefer the latter method (b), since we usually know where our divs are. In <i>our_script.js</i>, let&#8217;s wait for the DOM to load and then create a 500px by 500px<br />
            canvas inside our <i>canvas_container</i> div:</p>
<pre name="code" class="js">
window.onload = function() {
    var paper = new Raphael(document.getElementById('canvas_container'), 500, 500);
}
        </pre>
<p>All our drawing methods will now be bound to the <i>paper</i> variable.</p>
<h3>3. Built-in Shapes</h3>
<p>Now that we have our canvas, let&#8217;s draw some shapes onto it. The <i>origin</i>, that is, the x = 0, y = 0 point, is at the top-left corner of<br />
            our canvas. This means that any x, y coordinates we specify in our methods are relative to this point.</p>
<p>First off, a <b>circle</b>. Modify <i>our_script.js</i> to look like this:</p>
<pre name="code" class="js">
window.onload = function() {
    var paper = new Raphael(document.getElementById('canvas_container'), 500, 500);
    var circle = paper.circle(100, 100, 80);
}
        </pre>
<p>This will draw a circle with a radius of 80px with its center placed at x = 100, y = 100. We can draw as many circles as we like and we don&#8217;t <i>have</i> to<br />
        reference them in a variable:</p>
<pre name="code" class="js">
for(var i = 0; i < 5; i+=1) {
    var multiplier = i*5;
    paper.circle(250 + (2*multiplier), 100 + multiplier, 50 - multiplier);
}
        </pre>
<p>Next, let's draw a <b>rectangle</b>. We do this using the rect() method, which takes as parameters: the x and y coordinates of the rectangle's top-left corner and the<br />
            rectangle's desired width and height.</p>
<pre name="code" class="js">
var rectangle = paper.rect(200, 200, 250, 100);
        </pre>
<p>Finally, we'll draw an <b>ellipse</b>. Its parameters are the same as the circle, i.e. x, y, radius, except that we can specify x and y radii specifically. </p>
<pre name="code" class="js">
var ellipse = paper.ellipse(200, 400, 100, 50);
        </pre>
<p>This will draw an ellipse with x-radius = 100, y-radius = 50 at x = 200, y = 400. Our <i>our_script.js</i> file should now look like this:</p>
<pre name="code" class="js">
window.onload = function() {
    var paper = new Raphael(document.getElementById('canvas_container'), 500, 500);
    var circle = paper.circle(100, 100, 80);
    for(var i = 0; i < 5; i+=1) {
        var multiplier = i*5;
        paper.circle(250 + (2*multiplier), 100 + multiplier, 50 - multiplier)
    }
    var rectangle = paper.rect(200, 200, 250, 100);
    var ellipse = paper.ellipse(200, 400, 100, 50);

}
        </pre>
<p>If we now open up <i>index.htm</i> in our browser, we should get a bunch of shape drawings:</p>
<div class="tutorial_image"><img src="http://nettuts.s3.amazonaws.com/462_raphael/builtinshapes.jpg" border="0" width="400" /></div>
<p><b>Example <a href="http://www.emunch.co.uk/tutorials/raphael_tut/examples/simple_shapes.php">Here</a></b></p>
<h3>4. Drawing Paths</h3>
<p>While the built-in shapes are handy to have, it is <i>paths</i> that offer us true drawing flexibility.<br />
            When drawing paths, it helps to think of an imaginary cursor or pen-point pressed against the screen. When we create our canvas, the cursor is rooted to the<br />
        top-left corner. The first thing we should do, then, is<br />
        lift up our cursor or pen-point and move it to a spacious region in which we can draw.</p>
<p>As an example, let's move our cursor to the centre of our canvas. That is, let's move it 250px in the x-direction and move it 250px in the y-direction.</p>
<div class="tutorial_image"><img src="http://nettuts.s3.amazonaws.com/462_raphael/move_to_centre.jpg" border="0" /></div>
<p>We do this using a so-called <i>path string</i>.</p>
<p>A path string is a string comprised of 'action' commands and numeric values corresponding to the command. We move our cursor to x = 250, y = 250 using the following<br />
            string:</p>
<pre name="code" class="js">
"M 250 250"
        </pre>
<p>'M' means we want to <i>move without drawing</i> and is followed by x and y canvas co-ordinates.</p>
<p>Now that our cursor is where we want it, let's draw a line <i>relative to this point</i> using the lower-case 'L' command, 'l'.</p>
<pre name="code" class="js">
"M 250 250 l 0 -50"
        </pre>
<p>This will draw a line <i>upwards</i> 50px in the y-direction. Let's write a path string that will draw a tetris tetronimo:</p>
<pre name="code" class="js">
"M 250 250 l 0 -50 l -50 0 l 0 -50 l -50 0 l 0 50 l -50 0 l 0 50 z"
        </pre>
<p>The 'z' command signifies the path closing - it will join a line from wherever we are to the point specified by our initial 'M' command.</p>
<p>We tell Raphael to actually draw this path using the path() method. Modify <i>our_script.js</i> to look like this:</p>
<pre name="code" class="js">
window.onload = function() {
    var paper = new Raphael(document.getElementById('canvas_container'), 500, 500);
    var tetronimo = paper.path("M 250 250 l 0 -50 l -50 0 l 0 -50 l -50 0 l 0 50 l -50 0 l 0 50 z");
}
        </pre>
<p>If you load up <i>index.htm</i>, you should now see a tetronimo like this:</p>
<div class="tutorial_image"><img src="http://nettuts.s3.amazonaws.com/462_raphael/tetronimo.jpg" border="0" /></div>
<p> Path strings can become incredibly (brilliantly) complex using curve and arc commands. Full coverage of paths can be found at the<br />
            <a href="http://www.w3.org/TR/SVG/paths.html#PathData">SVG Path specification</a> page.</p>
<h3>5. Attribute Styling</h3>
<p>Our tetris tetronimo, whilst wonderful, is not very aesthetically pleasing. We'll fix that using the attr() method.</p>
<p>The attr() method takes an object consisting of various property-value pairs as its parameter. Since we stored a reference to our tetronimo in the variable <i>tetronimo</i>, we can take this variable and add the attr() method to it. We could equally well<br />
            chain the attr() method to the path() method, but let's keep things sane for the time being. I'll demonstrate the use of attr() by example:</p>
<pre name="code" class="js">
window.onload = function() {
    var paper = new Raphael(document.getElementById('canvas_container'), 500, 500);
    var tetronimo = paper.path("M 250 250 l 0 -50 l -50 0 l 0 -50 l -50 0 l 0 50 l -50 0 l 0 50 z");

    tetronimo.attr({fill: '#9cf', stroke: '#ddd', 'stroke-width': 5});
}
        </pre>
<p>produces this:</p>
<div class="tutorial_image"><img src="http://nettuts.s3.amazonaws.com/462_raphael/tetronimo_filled_02.jpg" border="0" /></div>
<pre name="code" class="js">
window.onload = function() {
    var paper = new Raphael(document.getElementById('canvas_container'), 500, 500);
    var tetronimo = paper.path("M 250 250 l 0 -50 l -50 0 l 0 -50 l -50 0 l 0 50 l -50 0 l 0 50 z");

    tetronimo.attr(
        {
            gradient: '90-#526c7a-#64a0c1',
            stroke: '#3b4449',
            'stroke-width': 10,
            'stroke-linejoin': 'round',
            rotation: -90
        }
    );
}
        </pre>
<p>produces this:</p>
<div class="tutorial_image"><img src="http://nettuts.s3.amazonaws.com/462_raphael/tetronimo_gradient.jpg" border="0" width="400" /></div>
<p>The Raphael <a href="http://raphaeljs.com/reference.html#attr">documentation</a> is pretty extensive when it comes to the attr() method.<br />
            Have a play around with the various object property-value combinations.</p>
<h3>6. Animation</h3>
<p>The animate() method in Raphael is really, <i>really</i> good. It allows us to animate our drawings in a jQuery-esque manner, animating<br />
        the attributes we supply it over some period of time with an optional easing.</p>
<p>Let's rotate our most recent tetronimo by 360 degrees. The rotation<br />
        attribute is absolute, so this should take it one full rotation and bring it back to its un-rotated state.</p>
<pre name="code" class="js">
window.onload = function() {
    var paper = new Raphael(document.getElementById('canvas_container'), 500, 500);
    var tetronimo = paper.path("M 250 250 l 0 -50 l -50 0 l 0 -50 l -50 0 l 0 50 l -50 0 l 0 50 z");
    tetronimo.attr(
        {
            gradient: '90-#526c7a-#64a0c1',
            stroke: '#3b4449',
            'stroke-width': 10,
            'stroke-linejoin': 'round',
            rotation: -90
        }
    );

    tetronimo.animate({rotation: 360}, 2000, 'bounce');
}
        </pre>
<p>The animation takes place over 2 seconds (2000 milliseconds) and is told to ease into its final state with a 'bounce'.</p>
<p><b>Example <a href="http://www.emunch.co.uk/tutorials/raphael_tut/examples/rotate_tetronimo.php">here</a></b>.</p>
<p>We can also supply a callback function as an argument. This callback function is invoked after the animation finishes. The following example<br />
            will animate the tetronimo's rotation and stroke-width and then reset itself with another animation in the callback function.</p>
<pre name="code" class="js">
tetronimo.animate({rotation: 360, 'stroke-width': 1}, 2000, 'bounce', function() {
    /* callback after original animation finishes */
    this.animate({
        rotation: -90,
        stroke: '#3b4449',
        'stroke-width': 10
    }, 1000);
});
        </pre>
<p>The <i>this</i> keyword references the original tetronimo from within the callback function.</p>
<p><b>Example <a href="http://www.emunch.co.uk/tutorials/raphael_tut/examples/rotate_tetronimo_callback.php">here</a>.</b></p>
<h4>Animating Paths</h4>
<p>Being a bit of a code geek, I rarely ever got past drawing simple shapes in Flash. But one thing I liked playing with was <i>shape tweening</i>. Well,<br />
            Raphael goes some way to emulating shape tweening by specifying a path string in the animate() method.</p>
<p>Another tetronimo, the Z tetronimo in Tetris, has the following path string,</p>
<pre name="code" class="js">"M 250 250 l 0 -50 l -50 0 l 0 -50 l -100 0 l 0 50 l 50 0 l 0 50 z"</pre>
<p>and it looks like this:</p>
<div class="tutorial_image"><img src="http://nettuts.s3.amazonaws.com/462_raphael/z_tetronimo.jpg" border="0" /></div>
<p>Now, using our original tetronimo with minimal attribute styling, i'm going to specify the new path string in our animate() method.</p>
<pre name="code" class="js">
tetronimo.attr(
    {
        stroke: 'none',
        fill: 'blue'
    }
);

tetronimo.animate({
    path: "M 250 250 l 0 -50 l -50 0 l 0 -50 l -100 0 l 0 50 l 50 0 l 0 50 z"
}, 5000, 'elastic');
        </pre>
<p>You should see our original tetronimo morph into our new one. The effect is made all the more pronounced by specifying 'elastic' as the easing type.</p>
<p><b>Example <a href="http://www.emunch.co.uk/tutorials/raphael_tut/examples/tween_tetronimo.php">here</a>.</b></p>
<h3>7. Dom Accessibility</h3>
<p>If we want to get access to our elements as DOM elements, we can do so with some ease. This is thanks to the <i>node</i> property. Using this, we can<br />
        add event handlers to our drawings, which i'll proceed to show you.</p>
<p>Let's start by drawing a circle in our <i>our_script.js</i> file.</p>
<pre name="code" class="js">
window.onload = function() {
        var paper = new Raphael(document.getElementById('canvas_container'), 500, 500);

        var circ = paper.circle(250, 250, 40);
        circ.attr({fill: '#000', stroke: 'none'});
}
        </pre>
<p>Now, let's add the text, 'Bye Bye Circle!' so that its center point is at the same point as our circle center.</p>
<pre name="code" class="js">
var text = paper.text(250, 250, 'Bye Bye Circle!')
text.attr({opacity: 0, 'font-size': 12}).toBack();
        </pre>
<p>I have set the opacity to 0 so that it is initially hidden. Notice the chaining of the toBack() method. This places the text behind all other<br />
            canvas drawing elements (similarly, toFront() brings elements to the very front of our canvas).</p>
<p>Now, let's add a mouseover event handler to our circle using the node property. We will set the cursor style to 'pointer'.</p>
<pre name="code" class="js">
circ.node.onmouseover = function() {
    this.style.cursor = 'pointer';
}
        </pre>
<p>What this actually does is set the style property of the &lt;circle> object in our document. Our document looks like this:</p>
<pre name="code" class="html">
&lt;circle cx="250.5" cy="250.5" r="40" fill="#000000" stroke="none" style="fill: #000000; stroke: none; cursor: pointer">
&lt;/circle>
        </pre>
<p>Now, let's finally add an onclick event handler to our circle:</p>
<pre name="code" class="js">
circ.node.onclick = function() {
    text.animate({opacity: 1}, 2000);
    circ.animate({opacity: 0}, 2000, function() {
        this.remove();
    });
}
        </pre>
<p>When the circle is clicked, the text we referenced in the variable <i>text</i> is animated to full opacity over 2 seconds. The circle itself is animated<br />
            to 0 opacity over the same time period. We also include a callback function in the circle's animate method. This removes the<br />
            the circle element from our document once the animation has finished, since whilst the circle has 0 opacity, it is still clickable until removed.</p>
<p><b>Example <a href="http://www.emunch.co.uk/tutorials/raphael_tut/examples/onclick_make_circle_disappear.php">here</a>.</b></p>
<h3>8. Let's Build a Widget</h3</p>
<p>Finally, let's pull together what we've learned and build a pretty little Mood Meter. Basically, you will select a mood value between 1 and 5, 1 being 'rubbish' and<br />
            5 being 'positvely manic', and Raphael will create a nice representation of this.</p>
<p><b>View the widget <a href="http://www.emunch.co.uk/tutorials/raphael_tut/examples/mood_widget.php">here</a></b></p</p>
<div class="tutorial_image"><img src="http://nettuts.s3.amazonaws.com/462_raphael/mood_meter.jpg" border="0" /></div>
<p>Begin by modifying <i>our_script.js</i> to look like this:</p>
<pre name="code" class="js">
window.onload = function() {
    var paper = new Raphael(document.getElementById('canvas_container'), 500, 500);
    var circ = paper.circle(250, 250, 20).attr({fill: '#000'});
    var mood_text = paper.text(250, 250, 'My\nMood').attr({fill: '#fff'});
}
        </pre>
<p>This creates a circle of radius 20px at the center of our canvas and some text on top of the circle saying 'My Mood'. 'Mood' is placed on a new line using<br />
            '\n'.</p>
<p>Next, let's create some custom information corresponding to our moods and choose which mood we're in.</p>
<pre name="code" class="js">
moods = ['Rubbish', 'Not Good', 'OK', 'Smily', 'Positively Manic'];
colors = ['#cc0000', '#a97e22', '#9f9136', '#7c9a2d', '#3a9a2d'];

//pick a mood between 1 and 5, 1 being rubbish and 5 being positively manic
var my_mood = 1;
        </pre>
<p>The text description of our mood is stored in an array called 'moods' and the color corresponding to this mood is stored in an array called 'colors'.<br />
            The chosen mood, a value between 1 and 5, is stored in the variable my_mood.</p>
<p>Now let's create a function called show_mood. When invoked, this function will display our mood circles (the colored circles) and the text corresponding to this mood.</p>
<pre name="code" class="js">
function show_mood() {

    for(var i = 0; i < my_mood; i+=1) {
        (function(i) {
            setTimeout(function() {
                paper.circle(250, 250, 20).attr({
                    stroke: 'none',
                    fill: colors[my_mood - 1]
                }).animate({translation: '0 ' + (-42 * (i+1))}, 2000, 'bounce').toBack();
            }, 50*i);
        })(i);
    }
    paper.text(250, 300, moods[my_mood - 1]).attr({fill: colors[my_mood - 1]});

    mood_text.node.onclick = function() {
        return false;
    }
    circ.node.onclick = function() {
        return false;
    }

}
        </pre>
<p>In show_mood(), we have a loop that iterates as many times as the value of my_mood. Inside this loop is a self-executing anonymous function. This is necessary so that<br />
            we have access to the variable <i>i</i> at each stage of the iteration. Inside the self-executing function, we create a timeout - every 50*i seconds, a circle<br />
            is created at the point of our original circle. Each circle is then translated over 2 seconds to 0px in x and some multiple of -42px in y. We make sure to place<br />
            each successive circle at the back of the canvas. Note that the circles are filled according to the color in the colors array, determined by my_mood.</p>
<p>show_mood() is also responsible for the display of our mood text which uses my_mood to pick the corresponding mood from the moods_array.</p>
<p>show_mood() then finally get rid of any onclick event handlers assigned to the original text and circle we placed at the center of the canvas. This prevents<br />
            the re-drawing of moods circles.</p>
<p>Finally, let's assign onclick event handlers to the center circle and 'My Mood' text. I assign event handlers to both elements so that clicking on either<br />
            the text or circle has the effect of calling show_mood().</p>
<pre name="code" class="js">
circ.node.onclick = show_mood;
mood_text.node.onclick = show_mood;
</pre>
<h3>Conclusion</h3>
<p>Well, that's it! You should now have a sound platform on which to base your explorations into the Raphael JS framework. Most importantly, I hope<br />
            you're now eager to delve into Raphael JS and concoct some beautiful browser drawings and widgets. Don't forget to follow me on <a href="http://www.twitter.com/damiandawber">Twitter</a>, and share your creations.</p>
<ul class="webroundup">
<li>Follow us on <a href="http://www.twitter.com/nettuts">Twitter</a>, or subscribe to the <a href="http://feeds.feedburner.com/nettuts" title="Nettuts+ RSS Feed">Nettuts+ RSS Feed</a> for more daily web development tuts and articles.</li>
</ul>
<p>
<script type="text/javascript"><!--digg_url = "post permalink (not digg url)"; // -->
</script><br />
<script src="http://digg.com/tools/diggthis.js" type="text/javascript"></script></p>
]]></content:encoded>
			<wfw:commentRss>http://net.tutsplus.com/tutorials/javascript-ajax/an-introduction-to-the-raphael-js-library/feed/</wfw:commentRss>
		<slash:comments>37</slash:comments>
		</item>
		<item>
		<title>Create an In-Place Editing System</title>
		<link>http://net.tutsplus.com/tutorials/javascript-ajax/create-an-in-place-editing-system/</link>
		<comments>http://net.tutsplus.com/tutorials/javascript-ajax/create-an-in-place-editing-system/#comments</comments>
		<pubDate>Tue, 22 Sep 2009 11:38:05 +0000</pubDate>
		<dc:creator>Siddharth</dc:creator>
				<category><![CDATA[JavaScript & AJAX]]></category>

		<guid isPermaLink="false">http://net.tutsplus.com/?p=6843</guid>
		<description><![CDATA[<img src="http://nettuts.s3.amazonaws.com/443_editing/demo/200x200.jpg" alt="Create an In-Place Editing System" />]]></description>
			<content:encoded><![CDATA[<p>Making users click through multiple pages just to edit a field is so 1999. In this tutorial, you&#8217;ll learn how to create an in-place editing system as found on popular sites, such as Flickr.</p>
<p><span id="more-6843"></span></p>
<div class="tutorial_image">
<a href="http://nettuts.s3.amazonaws.com/443_editing/demo.zip"><img src="http://nettuts.com/wp-content/themes/nettuts/site_images/button_src_nm.jpg"></a><br />
<a href="http://nettuts.s3.amazonaws.com/443_editing/demo/code.html"><img src="http://nettuts.com/wp-content/themes/nettuts/site_images/button_demo_nm.jpg"></a>
</div>
<h3>A word from the Author</h3>
<p>With all the buzz around Web 2.0, ease of use is now much more important than ever. Being able to edit some content without having to go to another page is something a lot of users really crave. A lot of big names are already using this pattern to great effect. If you&#8217;ve used Flickr, you&#8217;ve probably seen this in action.  </p>
<p>I believe a demo is worth a thousand words. Hit the demo and try it out yourselves. </p>
<p>Today, we are going to look at how to implement this with, you guessed it right, our favorite JavaScript library, jQuery. Interested? Let&#8217;s get started right away!</p>
<h3>Design Goals</h3>
<p>Before we start looking at how to implement the functionality, here are a few thoughts about the goals and the resulting decisions.</p>
<ul>
<li>We need to let  the user edit the content without leaving the page. This is a given.</li>
<li>This should either function as a whole or fail as a whole. When JS is disabled, we don&#8217;t want to run into weird quirks.</li>
<li>The user should know the content is editable. A subtle blue background change should draw the user&#8217;s attention to this.</li>
<li>When dealing with how to trigger the edit there are a few options. We can either let the user edit on a normal click or double click. I&#8217;ve chosen double click since random double clicks occur at a smaller rate than random clicks. Switching it is just a matter of changing the parameter in the bind event.</li>
<li>A way for the user to save or discard the edits.</li>
<li>Save or edit events can be triggered by 2 ways. Keyboard events or mouse events. I chose mouse events since keyboard events lack specificity.</li>
<li>With respect to mouse events, you could use either traditional buttons or usual links. I chose links for no particular reason.</li>
<li>The user should be able to resume editing even if he clicks outside of the input box or leaves the page and comes back.</li>
<li>Additionally, the user should be able to edit as many fields as possible simultaneously.</li>
</ul>
<p>Now that we&#8217;ve mapped out our needs we can now move on to how we are going to do this.</p>
<h3>Plan of Action</h3>
<p>We&#8217;ll now need to map out what needs to be done in a specific order.</p>
<p><strong>Step 1:</strong> We&#8217;ll need to add a class of <em>editable</em> to each elements which need this functionality. </p>
<p><strong>Step 2:</strong> We&#8217;ll next need to add hovers to each editable item to draw attention to the fact that that item&#8217;s content is editable. We&#8217;ll add and remove the hovers using JavaScript instead of CSS. This is mainly done for devices or browsers with JavaScript  disabled. We don&#8217;t want to send them wrong visual cues.</p>
<p><strong>Step 3:</strong> When an editable item is double clicked, we need to swap out the contents and replace it with a text box with the old text in it.</p>
<p><strong>Step 4a:</strong> When the user wants to save the edits, copy the input&#8217;s value to the parent element and remove the input box.</p>
<p><strong>Step 4b:</strong> Or when the user wants to discard the changes, replace the old content and remove the input box.</p>
<p>These are the basic steps in creating this functionality. Of course there are few other small things but I&#8217;ll explain them as we go along.</p>
<h3>Core Markup</h3>
<p>The HTML markup of the demo page looks like so.</p>
<pre name="code" class="html">
&lt;!DOCTYPE html&gt;
&lt;html lang="en-GB"&gt;
&lt;head&gt;
&lt;title&gt;In-place editing system - by Siddharth for NetTuts&lt;/title&gt;
&lt;link type="text/css" href="css/style.css" rel="stylesheet" /&gt;
&lt;script type="text/javascript" src="js/jquery.js"&gt;&lt;/script&gt;
&lt;script type="text/javascript" src="js/mojo.js"&gt;&lt;/script&gt;
&lt;/head&gt;
&lt;body&gt;

&lt;div id="container"&gt;

&lt;h1&gt;In-place editing&lt;/h1&gt;
&lt;div&gt;by Siddharth for the lovely folks at Net Tuts&lt;/div&gt;
&lt;p&gt;Elements with a class of &lt;em&gt;editable&lt;/em&gt; are, well, editable. In case you haven't noticed, all
elements containing the &lt;em&gt;editable&lt;/em&gt; class get a blue background on hover to indicate this capability. &lt;/p&gt; 

&lt;p&gt;Double click to edit the contents. Use the dynamically created links to save or discard the changes.
You can open up as many fields to edit as you want without any hiccups.&lt;/p&gt;

&lt;div class="block"&gt;
&lt;h2&gt;I &lt;/h2&gt;
&lt;ul&gt;
&lt;li class="editable"&gt;am Siddharth&lt;/li&gt;
&lt;li class="editable"&gt;love working with the web&lt;/li&gt;
&lt;li class="editable"&gt;am a freelancer&lt;/li&gt;
&lt;li class="editable"&gt;write for Net Tuts&lt;/li&gt;
&lt;li class="editable"&gt;can be found at &lt;a href="http://www.ssiddharth.com"&gt;www.ssiddharth.com&lt;/a&gt;&lt;/li&gt;
&lt;li class="editable"&gt;will never let you down or give you up <img src='http://net.tutsplus.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> &lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;

&lt;div class="block"&gt;
&lt;h2&gt;Things to do this week&lt;/h2&gt;
&lt;ul&gt;
&lt;li class="editable"&gt;Get design approval from Deacon&lt;/li&gt;
&lt;li class="editable"&gt;Send an invoice to Albert &lt;/li&gt;
&lt;li class="editable"&gt;Start work on Dwight's project&lt;/li&gt;
&lt;li class="editable"&gt;Talk with Sarah about new ideas&lt;/li&gt;
&lt;li class="editable"&gt;Check Seth's site for rendering bugs&lt;/li&gt;
&lt;li class="editable"&gt;Meet with Clintson to discuss project&lt;/li&gt;
&lt;/ul&gt;
&lt;/div&gt;

&lt;/div&gt;
&lt;/body&gt;
&lt;/html&gt;
</pre>
<p>As you see, disregarding the boiler plate, we have two unordered lists. Each <em>li</em> element has a class of <em>editable</em> to denote that its content can be edited.</p>
<p>We&#8217;ve also included the jQuery library and our own script file. </p>
<h3>CSS Styling</h3>
<pre name="code" class="css">
body{
	font-family: "Lucida Grande", "Verdana", sans-serif;
	font-size: 12px;
}

a{
	color: #000;
}

a:hover{
	text-decoration: none;
}

p{
	margin: 30px 0 10px 0;
}

h1{
	font-size: 30px;
	padding: 0;
	margin: 0;
}

h2{
	font-size: 20px;
}

#container{
	width: 820px;
	margin-left: auto;
	margin-right: auto;
	padding: 50px 0 0 0;

}

.editHover{
	background-color: #E8F3FF;
}

.editBox{
	width: 326px;
	min-height: 20px;
	padding: 10px 15px;
	background-color: #fff;
	border: 2px solid #E8F3FF;
}

ul{
	list-style: none;
}

li{
	width: 330px;
	min-height: 20px;
	padding: 10px 15px;
	margin: 5px;
}

li.noPad{
	padding: 0;
	width: 360px;
}

form{
	width: 100%;
}

.btnSave, .btnCancel{
	padding: 6px 30px 6px 75px;
}

.block{
	float: left;
	margin: 20px 0;
}
</pre>
<p>Nothing special here. Just a bunch of code for layout and styling purposes.</p>
<p>Take special note of the <em>editHover</em> and <em>noPad</em> classes. We&#8217;ll be using them in a bit.</p>
<h3>JavaScript Implementation</h3>
<p>Now that we have a solid framework and some basic styling in place, we can start coding up the required functionality. Do note that we make extensive use of jQuery. Specifically we&#8217;ll need at least version 1.3 or higher. Anything less and it won&#8217;t work. </p>
<h3>Adding Hovers</h3>
<div class="tutorial_image">
   <img src="http://nettuts.s3.amazonaws.com/443_editing/demo/hover.png" alt="Hovers" />
</div>
<p>As noted earlier, we&#8217;ll need to add a subtle blue background to editable objects to signify they are editable. We&#8217;ve already created the <em>editHover</em> class to take care of this.</p>
<pre name="code" class="js">
$(".editable").hover(
		function()
		{
			$(this).addClass("editHover");
		},
		function()
		{
			$(this).removeClass("editHover");
		}
	);
</pre>
<p>This tiny snippet takes care of that for us. We use jQuery&#8217;s <em>hover</em> method to add the <em>editHover</em> class when the element is hovered upon and remove it when it is not. We use <em>this</em> to refer to the specific element that is hovered over. If we had used <em>.editable</em> as the selector instead each and every element will get the class added to it. So we use <em>this</em> to target only the  element we need.</p>
<h3>Switching out the Elements</h3>
<p>First up, we need to make sure our code is executed when the target element is double clicked. So we&#8217;ll first hook up the handler for this event first.</p>
<pre name="code" class="js">
$(".editable").bind("dblclick", replaceHTML);
</pre>
<p>We attach the <em>replaceHTML</em> function to the <em>double click</em> event relative to the <em>editable</em> element with that one liner. Now we can move on the switching out the elements.</p>
<pre name="code" class="js">
function replaceHTML()
	{
		oldText = $(this).html()
						 .replace(/"/g, "&quot;");
		$(this).html("")
			   .html("&lt;form&gt;&lt;input type=\"text\" class=\"editBox\"
			    value=\"" + oldText + "\" /&gt; &lt;/form&gt;&lt;a href=\"#\" class=\"btnSave\"&gt;Save changes&lt;/a&gt;
		        &lt;a href=\"#\" class=\"btnDiscard\"&gt;Discard changes&lt;/a&gt;");
	}
</pre>
<p>Let&#8217;s go over our code bit by tiny bit.</p>
<p>I define the functionality inside a separate named function instead of an anonymous function for a specific reason: I&#8217;ll be using this function more than once. Next, we save the content of the element for future use using jQuery&#8217;s <em>html</em> method and replacing all quotes since it messes up our output down the line. </p>
<p>Now that our content is safely stored for later use, we can switch out the elements. First we empty out the <em>li</em> element by sending in an empty string to the <em>html</em> method. Next, we insert some standard HTML for an input box. We add some classes to it for styling purposes. More importantly, we set its <em>value</em> attribute to the original text contained by the element stored in <em>oldText</em>. We also add a couple of links to take care of saving and discarding the edits. We&#8217;ve also added classes to them so they can be targeted easily and for styling.</p>
<p>As always, we use <em>this</em> to target the element which triggered the event.</p>
<h3>Keeping the Edits</h3>
<div class="tutorial_image">
   <img src="http://nettuts.s3.amazonaws.com/443_editing/demo/edited.png" alt="Edited Text" />
</div>
<pre name="code" class="js">
$(".btnSave").live("click",
	function()
	{
		newText = $(this).siblings("form")
						 .children(".editBox")
						 .val().replace(/"/g, "&quot;");

		$(this).parent()
			   .html(newText);
	}
);
</pre>
<p>First up, let me introduce jQuery&#8217;s <em>live</em> method. You probably haven&#8217;t seen this much before so I&#8217;ll give a quick introduction. </p>
<blockquote><p>You can&#8217;t hook up handlers to events triggered by elements which are not even present in the DOM when the page and the JavaScript was loaded. If you use normal event binding functions, it&#8217;ll fail due to the above mentioned reason. The <em>live</em> method takes care of that. </p>
</blockquote>
<p>It binds handlers to events irrespective of when the element was created. For more about this, you can go through the <a href="http://docs.jquery.com/Events/live#typefn">official docs</a>. </p>
<p>Lets look into our code now. We first bind the code contained within our anonymous function to the <em>click</em> event. Inside the function we first save the text contained in the input box. This can be a little tricky since the input box doesn&#8217;t have an ID. So we first look for the form element which happens to be its sibling and then traverse through to find the input element. We then copy its value after replacing all the quotes it may contain. </p>
<p>Next, we obtain the links parent element, the <em>li</em> element and replace its HTML content with the text we copied in the previous step. </p>
<p>This block could have easily been created as a one liner but I chose to split it to 2 lines in the interest of readability.</p>
<h3>Discarding the Edits</h3>
<pre name="code" class="js">
$(".btnDiscard").live("click",
	function()
	{
		$(this).parent()
			   .html(oldText);
	}
);
</pre>
<p>This is just as simple as it looks. Since the user doesn&#8217;t want to keep any of the edits. We just replace the HTML content of parent element with the original text we had copied earlier to the <em>oldText</em> variable. </p>
<p>With this the core of our work is done. We just need to do a couple of edits to make sure things don&#8217;t break when the user does unexpected things.</p>
<h3>Binding and Unbinding</h3>
<p>If you&#8217;ve tested out our code at this point you&#8217;ll probably end up with this functionality breaking bug: When a user double clicks in the resulting input box it is now filled with the HTML content of the editing system. Try it yourself. With each double click, the value of the input box reflects by adding another bunch of text to it. This issue will probably be a lot worse if you&#8217;ve chosen click as the trigger event. </p>
<p>To rectify this, we need to unbind the event handler for that specific element alone and rebind them as soon as the user clicks either save or discard. Let&#8217;s implement that now.</p>
<p>Our previous blocks of code now need to be edited out to so:</p>
<pre name="code" class="js">
function replaceHTML()
	{
		//Code
		$(this).html("")
		// Earlier form insertion code
                .unbind('dblclick', replaceHTML);
	}
</pre>
<p>We unhook the handler for the element which triggered the event. The rest of the elements with the <em>editable</em> class still have their handlers intact and will respond to events.</p>
<pre name="code" class="js">
$(".btnSave").live("click",
	function()
	{
		// Earlier code

		$(this).parent()
			   .html(newText)
                           .bind("dblclick", replaceHTML);
	}
);
</pre>
<pre name="code" class="js">
$(".btnDiscard").live("click",
	function()
	{
		$(this).parent()
			   .html(oldText)
                           .bind("dblclick", replaceHTML);
	}
);
</pre>
<p>Next we attach those handlers back in spite of whether the user chooses to edit them or not. If we don&#8217;t re-attach these, the fields can be edited only once. The second time they are double clicked, the handlers are no longer attached to the events. We rectify this by hooking the handlers back to the events.</p>
<h3>A Few Tweaks</h3>
<p>This last bit of code is purely to spruce up the appearance of our effect. If you&#8217;ve noticed, the <em>li</em> has a bit of padding in place to make the text within look better. But when the text is stripped out and replaced by a text box we result looks ugly and breaks the effect. We want the text box to take up exactly the same space the original text took. With this in mind, we add a <em>noPad</em> class to the element when it has been double clicked and removed again when the user saves or discards the edit. </p>
<pre name="code" class="js">
function replaceHTML()
	{
		//Code
		$(this).addClass("noPad")
                    		.html("")
		// Earlier code
	}
</pre>
<p>We unhook the handler for the element which triggered the event. The rest of the elements with the <em>editable</em> class still have their handlers intact and will respond to events.</p>
<pre name="code" class="js">
$(".btnSave").live("click",
	function()
	{
		// Earlier code

		$(this).parent()
			   .removeClass("noPad")
                // Earlier code
	}
);
</pre>
<pre name="code" class="js">
$(".btnDiscard").live("click",
	function()
	{
		$(this).parent()
			   .removeClass("noPad")
                           // Earlier code
	}
);
</pre>
<h3>The Complete Code</h3>
<p>Here is how the complete code looks like:</p>
<pre name="code" class="js">
$(document).ready(function()
{
	var oldText, newText;

  	$(".editable").hover(
					function()
					{
						$(this).addClass("editHover");
					},
					function()
					{
						$(this).removeClass("editHover");
					}
					);

  	$(".editable").bind("dblclick", replaceHTML);

	$(".btnSave").live("click",
					function()
					{
						newText = $(this).siblings("form")
										 .children(".editBox")
										 .val().replace(/"/g, "&quot;");

						$(this).parent()
							   .html(newText)
							   .removeClass("noPad")
							   .bind("dblclick", replaceHTML);
					}
					); 

	$(".btnDiscard").live("click",
					function()
					{
						$(this).parent()
							   .html(oldText)
							   .removeClass("noPad")
							   .bind("dblclick", replaceHTML);
					}
					); 

	function replaceHTML()
					{
						oldText = $(this).html()
										 .replace(/"/g, "&quot;");

						$(this).addClass("noPad")
							   .html("")
							   .html("&lt;form&gt;&lt;input type=\"text\" class=\"editBox\"
							    value=\"" + oldText + "\" /&gt; &lt;/form&gt;&lt;a href=\"#\" class=\"btnSave\"&gt;Save changes&lt;/a&gt;
							   .unbind('dblclick', replaceHTML);

					}
}
);
</pre>
<p>Not bad. Fifty odd lines to add some spiffy new functionality. </p>
<h3>Taking it One Step Further: The Backend</h3>
<p>In the interest of not making it too long, I&#8217;ve stuck to creating the client side functionality alone. If you want to implement this functionality within your own projects, its implicitly assumed that you&#8217;d need a back-end system in place to save these changes and more importantly, you&#8217;d need an AJAX request for making this call asynchronously.</p>
<p>Adding this functionality should be a cinch but do make a note of this. The code above was created just to illustrate this pattern and not for production use. So I&#8217;ve abstained from adding additional IDs attributes to elements and name attributes to text boxes. In your production code, do add all of them so the text box&#8217;s name attribute can be set meaningfully and in such a way the back end can recognize which piece of data needs to be updated. </p>
<p>To add an AJAX request, our save handler would have to be updated to so:</p>
<pre name="code" class="js">
$(".btnSave").live("click",
	function()
	{
		newText = $(this).siblings("form")
			 .children(".editBox")
			 .val().replace(/"/g, "&quot;");

                 $.ajax({
			type: "POST",
	 	url: "handler.php",
			data: newText,
			success: function(msg){
			 // Some code here to reflect a successful edit;
			}
			});

		$(this).parent()
			   .html(newText)
			   .removeClass("noPad")
			   .bind("dblclick", replaceHTML);
	}
);
</pre>
<p>Remember, for the back-end to make any sense of what you are sending to it, you need some additional data along with the updated text so the app knows which data to edit. You could easily send in more than one piece of data to the script if you need to. </p>
<h3>Conclusion</h3>
<p>And there you have it; how to add a  user friendly functionality to your projects. Hopefully you&#8217;ve found this tutorial interesting and this has been useful to you. Feel free to reuse this code elsewhere in your projects and chime in here if you are running into difficulties.</p>
<p>Questions? Nice things to say? Criticisms? Hit the comments section and leave me a comment. Happy coding!</p>
<ul class="webroundup">
<li>Follow us on <a href="http://www.twitter.com/nettuts">Twitter</a>, or subscribe to the <a href="http://feeds.feedburner.com/nettuts" title="Nettuts+ RSS Feed">Nettuts+ RSS Feed</a> for more daily web development tuts and articles.</li>
</ul>
<p>
<script type="text/javascript"><!--digg_url = "post permalink (not digg url)"; // -->
</script><br />
<script src="http://digg.com/tools/diggthis.js" type="text/javascript"></script></p>
]]></content:encoded>
			<wfw:commentRss>http://net.tutsplus.com/tutorials/javascript-ajax/create-an-in-place-editing-system/feed/</wfw:commentRss>
		<slash:comments>101</slash:comments>
		</item>
		<item>
		<title>Checking Username Availability with Mootools and Request.JSON</title>
		<link>http://net.tutsplus.com/tutorials/javascript-ajax/checking-username-availability-with-mootools-and-request-json/</link>
		<comments>http://net.tutsplus.com/tutorials/javascript-ajax/checking-username-availability-with-mootools-and-request-json/#comments</comments>
		<pubDate>Fri, 18 Sep 2009 17:30:24 +0000</pubDate>
		<dc:creator>Matt Vickers</dc:creator>
				<category><![CDATA[JavaScript & AJAX]]></category>
		<category><![CDATA[framework]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[json]]></category>
		<category><![CDATA[json.request]]></category>
		<category><![CDATA[MooTools]]></category>

		<guid isPermaLink="false">http://net.tutsplus.com/?p=6814</guid>
		<description><![CDATA[<img src="http://nettuts.s3.amazonaws.com/441_mootools/tutorial_img/preview.jpg" alt="Checking User Name availability using Mootools and Request.JSON" width="200" height="200"/>]]></description>
			<content:encoded><![CDATA[<p>This tutorial will teach you how to check username availability with Mootools&#8217; Request.JSON and PHP/MySQL</p>
<p><span id="more-6814"></span></p>
<div class="tutorial_image">
<a href="http://nettuts.s3.amazonaws.com/441_mootools/tutorial_img/ajax_check.zip"><img src="http://nettuts.com/wp-content/themes/nettuts/site_images/button_src_nm.jpg"></a>
</div>
<p>In this tutorial you will learn how to use Mootools&#8217; Request.JSON function to check a username against an array or database. In this example we will be using a simple MySQL database. I will try to do as much hand holding as I can, but having a little experience with PHP and MySQL will be a plus.</p>
<h3>Tutorial Details</h3>
<ul>
<li>PHP Server and MySQL Database required </li>
<li>Difficulty: Beginner/Intermediate </li>
<li>Estimated Completion Time: 30 &#8211; 45 Minutes </li>
</ul>
<p><!-- 600 --></p>
<h3>Step 1 &#8211; The Setup</h3>
<p>We are going to create a simple database and add a table. After that we will add a username into the database.</p>
<pre name="code" class="sql">
CREATE TABLE IF NOT EXISTS ajax_users (
	id INT(2) NOT NULL PRIMARY KEY AUTO_INCREMENT,
	user_name VARCHAR(128) NOT NULL
);

INSERT INTO ajax_users VALUES('NULL','matt');
</pre>
<p>Woohoo, we have a database, a table and a single username. Let&#8217;s get started with this tutorial!</p>
<h3>Step 2 &#8211; The Skeleton</h3>
<div class="tutorial_image">
<img src="http://nettuts.s3.amazonaws.com/441_mootools/tutorial_img/skeleton.png" alt="preview" width="600" height="253"/>
</div>
<p>For the first step we will create a simple page with one input field for the username and a submit button. Go ahead and open your favorite coding app &#8211; mine happens to be Coda &#8211; and create a new blank document named index.php. First I&#8217;ll show you the end result code for this step and then I&#8217;ll explain it in detail. I find that re-writting the code myself helps it stick, but you can copy and paste if you want.</p>
<pre name="code" class="html">
&lt;!--
	&lt;div id="container">

    	&lt;div id="content">

    		&lt;fieldset>

    			&lt;form method="post" action="" id="signup">

    				&lt;ul class="form">
    					&lt;li>
    						&lt;label for="user_name">Username&lt;/label>
    						&lt;input type="text" name="user_name" />
    					&lt;/li>
    					&lt;li>&lt;input type="submit" value="Sign Up Now!" />&lt;/li>
    				&lt;/ul>

    			&lt;/form>

    		&lt;/fieldset>

    	&lt;/div>

    &lt;/div>
-->
</pre>
<p>Now we&#8217;ve got a pretty basic site layout. It will start to come together in step 2 so don&#8217;t worry if it doesn&#8217;t really look like much right now. </p>
<h3>Step 3 &#8211; A little Style</h3>
<div class="tutorial_image">
<img src="http://nettuts.s3.amazonaws.com/441_mootools/tutorial_img/styled.png" alt="preview" width="600" height="253"/>
</div>
<p>Feel free to style this up however you like, or use the CSS file from the source code.</p>
<h3>Step 4 &#8211; The Javascript Setup</h3>
<p>We are going to need to include the Mootools framework into our php file. Without this, we can&#8217;t use any of Mootools&#8217; classes or functions for our script. There are two ways of doing this. The first way is to use Google&#8217;s AJAX Libraries API to link to the file. You can view the path <a href="http://code.google.com/apis/ajaxlibs/documentation/#mootools" target="_blank">Here</a>. The Google libraries give you access to many frameworks so take a look around after you&#8217;re done the tutorial. To speed things up, we can just use the piece of code below. Place this in your <head> section of your php file.</p>
<pre name="code" class="html">
&lt;script type="text/javacript" src="http://ajax.googleapis.com/ajax/libs/mootools/1.2.3/mootools-yui-compressed.js"></script>
</pre>
<p>The second way is to head over to the <a href="http://mootools.net" target="_blank">Mootools site</a></p>
<p>Now that we have the Mootools framework included in our file, we can go ahead and create a new file called main.js, or whatever you want to name it. Once this file has been created lets include it in our php file.</p>
<pre name="code" class="html">
&lt;script type="text/javacript" src="path-to-your-file/main.js"></script>
</pre>
<p>Go ahead and place that at the bottom of our php file. If you haven&#8217;t already, let&#8217;s open up our main.js file.</p>
<h3>Step 5 &#8211; The Mootools</h3>
<p>This part can get a little tricky. Make sure the two files you have open are index.php and main.js as we will be moving back and forth between the files to give you a better idea of how Mootools interacts with the elements in index.php.</p>
<p>The first piece of code we are going to add to main.js tells our Mootools script to execute some code when the DOM has loaded.</p>
<pre name="code" class="javascript">
	window.addEvent('domready', function() {
		//We are going to fill this with Mootools goodness
	});
</pre>
<p>Now that the main business is taken care of, we can get our hands dirty.</p>
<h3>Step 6 &#8211; Adding Events</h3>
<p>We need to figure out a way to find out when a user has interacted with our user name input field. We do this using events. Events are Mootools&#8217; way of performing some action(s) when a user does something. This can include clicking on a link, pressing down a key, releasing a key, mousing over etc. For this example we are going to fire an event when the user releases a key in the username field.</p>
<p>Before we add the event, we need to give out user name input an ID. Without an ID, Mootools doesn&#8217;t know which input we are talking about when we tell it to add an event.</p>
<p>Go ahead and add an ID to your user name input in index.php</p>
<pre name="code" class="html">
&lt;input type="text" name="user_name" id="user_name" />
</pre>
<p>Ok, I swear we will start coding some Mootools right now. Switch back to main.js. Inside your window event, add this code.</p>
<pre name="code" class="javascript">
$('user_name').addEvent('keyup',function(){
//This is what is fired when the user releases a key inside the username input
}
</pre>
<p>$(&#8217;user_name&#8217;) is what tells Mootools which element we are looking at. It relates to the elements ID.</p>
<p>After that we use .addEvent() to tell Mootools that we want to do something at some point. The first option is the event that we are watching for. We are using keyup. There are tons of other events we can look for. You can read about them at <a href="http://www.w3schools.com/html/html_eventattributes.asp" target="_blank">W3C Schools</a>. The last little bit holds a function that we will use to execute some JavaScript code whenever the event is fired.</p>
<h3>Step 7 &#8211; The Request</h3>
<p>Now that we have the event linked up, we can build the request to send when the event is fired. We are going to put this piece of code inside out event.</p>
<pre name="code" class="javascript">
	...
	The start of our event
	...

    	new Request.JSON({
    		url: "inc/php/json.php",
    		onSuccess: function(response){

    		}
    	}).get($('signup'));

	...
	The end of our event
	...
</pre>
<p>Pretty simple looking, eh?! We start off by declaring our request. The first variable is url. This is the path to our PHP that houses our JSON magic. For now, just put in a path to a future file. The second variable is onSuccess. This is a function that is fired if our request is successful. This is where we will put most of our remaining code. Our last little bit, which is easy to look over is the .get($(&#8217;signup&#8217;)) variable trailing our request. This takes all our info from our form in index.php and sends it with the JSON request. Without this, the request isn&#8217;t sending any data, and is pretty much useless. We&#8217;ve now made it useful!</p>
<p>We should probably make our JSON file right now so we don&#8217;t run into any errors.</p>
<h3>Step 8 &#8211; The JSON</h3>
<p>The concept behind our JSON file is pretty simple in theory. It takes our variables, does whatever we want with it, and then sends it back to our main.js file, all behind the scenes. This is awesome. Take a second to collect yourself.</p>
<p>Ok, now we are all calm, lets create a new file called json.php. If you added the path to your main.js file, name it the same and place it into proper folder. Open this sucker up!</p>
<pre name="code" class="php">
//setup a blank variable
//we will use this as an array to send back
$result = null;
</pre>
<p>Simple right? The first step is creating a null variable that we will be using as an array later on. Next, we need to connect to our database.</p>
<pre name="code" class="php">
//connect to the mysql database
mysql_connect('localhost', 'root', 'root') or die('Error connecting to mysql');
mysql_select_db('tutorials') or die('Error connecting to table');
</pre>
<p>We should be all connected. Fill in your database information above. To make sure everything is running smoothly, point to your json.php file. If the page is blank, we are golden. If you see database connection errors, we have a problem. This is usually just a misspelled host/username/password. Double check!</p>
<pre name="code" class="php">
//format the variables
$user_name = mysql_real_escape_string($_GET['user_name']);

//check the database for any users named $user_name
$grab_user = mysql_query("SELECT `user_name` FROM `ajax_users` WHERE `user_name` = '$user_name'");

//check if the query returned anything
if(mysql_num_rows($grab_user) == 0){

	//no user by that name
	$result['action'] = 'success';

}else{

	//oops, already taken
	$result['action'] = 'error';

}
</pre>
<p>All the variables sent to our json our sent as $_GET. If you&#8217;ve worked with forms before, this shouldn&#8217;t be anything different. If you haven&#8217;t worked with PHP forms before, please <a href="http://www.w3schools.com/PHP/php_get.asp" target="_blank">take a quick look at this page</a>.</p>
<p>We are putting the $_GET variable into a new variable to clean everything up. By wrapping the $_GET variable in the mysql_real_escape_string() function, we are making sure to combat mysql injection. Injection is bad!</p>
<p>Next is the query. We are grabbing any rows from our MySQL database where the user_name row is equal to whatever the user has typed into the user_name input. If the query returns 0, there is no user name match.</p>
<p>If there is no match, we add an action variable to our result array and give it a value of success. If there is a match, we simply give it a value of error.</p>
<pre name="code" class="php">
$result['user_name'] = $_GET['user_name'];

//send the response back
echo json_encode($result);
</pre>
<p>Finally, we add a user_name variable to the result array and give it a value of our $_GET variable and send it back to main.js using the json_encode() function.</p>
<p>When the JSON is encoded and sent back to the main.js file it looks like the code below</p>
<pre name="code">
{"action":"success","user_name":"matt"}
</pre>
<p>That ends the json file, you can save it and close it. You will not need it for this example anymore! Switch back to main.js</p>
<h3>Step 9 &#8211; Dealing with the Request</h3>
<p>We&#8217;ve sent the request, we&#8217;ve checked if the user name exists and we sent the response. So what now? Now we are going to use Mootools to sort through the response and alert the user. How does main.js see what the response is? If we take a quick look back at our onSuccess function, you&#8217;ll notice that the only variable passed in the function is response. This is the variable that now houses your JSON response. Please add this code inside our onSuccess function.</p>
<pre name="code" class="javascript">
if(response.action == 'success'){

	//We are good!

}else{

    //Username is taken, ouch?!
    alert('Username Taken');

}
</pre>
<p>We haven&#8217;t been able to test if our little application is even working right now, so lets take a second to do a quick test. Point your browser to index.php and type <em>matt</em> into your user_name input. Once you are done typing, <em>matt</em> an alert should popup saying <em>Username Taken</em>. You can now delete that alert; it is not needed anymore.</p>
<p>Alerts are boring. They&#8217;re ugly, they&#8217;re not very user friendly. Alerts are bad! We need a way to alert the user in a nice, design and user friendly way to alert the user. Open up your style.css and add some styles to your input.</p>
<div class="tutorial_image">
<img src="http://nettuts.s3.amazonaws.com/441_mootools/tutorial_img/error_notext.png" alt="preview" width="600" height="253"/>
</div>
<pre name="code" class="css">
input.success{
	border: 3px solid #9ad81f;
}

input.error{
	border: 3px solid #b92929;
}
</pre>
<p>We have our styles, and we are receiving a response, lets change the inputs style depending on the response.</p>
<pre name="code" class="javascript">
$('user_name').removeClass('error');
$('user_name').addClass('success');
</pre>
<div class="tutorial_image">
<img src="http://nettuts.s3.amazonaws.com/441_mootools/tutorial_img/ok_notext.png" alt="preview" width="600" height="253"/>
</div>
<p>We are taking our input and making sure Mootools can find it using $(). After that we add/remove our classes. We make sure to remove the error class incase the script has already added it to our input, then we add the success class. This stops the scripts from adding multiple classes to the input and making it look like input.error.success.error.success. For the response that throws an error, simply reverse the add/remove order.</p>
<p>Give that a test. The input box should have a green outline until you enter in <em>matt</em> as a user name. The input box should then turn red.</p>
<p>That&#8217;s it. That&#8217;s the bare bones version of this script. If you want, you can stop reading now and show-off your new tricks to your friends, or you can continue reading. I&#8217;m going to expand on the script to make it just a little bit more user friendly.</p>
<h3>Step 10 &#8211; 1000 Requests</h3>
<div class="tutorial_image">
<img src="http://nettuts.s3.amazonaws.com/441_mootools/tutorial_img/json_requests.png" alt="preview" width="600" height="253"/>
</div>
<p>Right now, the script is firing every time a user releases a key. What if you force users to have user names longer than 3 characters. We are basically wasting 3 requests when really, we can just tell the script not to fire unless the input value is more then 3 characters long. This will cut back on the number of requests we are sending to the JSON script!</p>
<pre name="code" class="javascript">
...
The start of our user name event
...

	var input_value = this.value;

	if(input_value.length > 3){

		...
		Request Event
		...

	}

...
The end of our user name event
...
</pre>
<p>If we wrap our request with the above code, it will only fire the request when the input value is greater than 3. First we put the value into our variable using this.value. <em>this</em> represents our user_name input. Next we check if the length of our value is greater than 3. We do this by using input_value.length. Give it a quick test.</p>
<h3>Step 11 &#8211; Visuals Please</h3>
<div class="tutorial_image">
<img src="http://nettuts.s3.amazonaws.com/441_mootools/tutorial_img/error_text.png" alt="preview" width="600" height="253"/>
</div>
<p>Remember in our JSON file we were sending our user name value back with our response. This is why. Open up index.php and add a p right underneath our input.</p>
<pre name="code" class="html">
&lt;p id="response">&lt;/p>
</pre>
<p>Now that we have our p with an id of response, we can make Mootools insert some text into it. Open up main.js and place this code inside the onSuccess function.</p>
<pre name="code" class="javascript">
$('response').set('html','&lt;em>'+response.user_name+'&lt;/em> is Available');
</pre>
<div class="tutorial_image">
<img src="http://nettuts.s3.amazonaws.com/441_mootools/tutorial_img/ok_text.png" alt="preview" width="600" height="253"/>
</div>
<p>Mootools takes $(&#8217;response&#8217;) and uses the set() function to insert some text. The first option is what kind of data are we setting. This can either be html or text. Because we are sending an <em></em> tag are a result, we are using html. We are using response.user_name to grab the user_name variable from our JSON response to keep the user up to date. For the error section, copy over the piece of code and change around the text a little bit to let the user know that the user name is taken.</p>
<h3>Step 12 &#8211; Submission</h3>
<p>Right now, even though we are saying that the user name is taken, the user can still submit the form. This means you would have to use PHP to do another level of error checking. You always want to make sure you are using PHP to make another level of error checking as it is possible for people to get around the disabling of the button. The more layers of security, the better! Open up index.php and find our submit button. Lets disable it!</p>
<pre name="code" class="html">
&lt;input type="submit" value="Sign Up Now!" id="submit_button" disabled="disabled" />
</pre>
<div class="tutorial_image">
<img src="http://nettuts.s3.amazonaws.com/441_mootools/tutorial_img/disabled.png" alt="preview" width="600" height="253"/>
</div>
<p>We gave out submit button an id of <em>submit_button</em> so that Mootools can talk to it. Near the close tag we also added <em>disabled</em>. If you point your browser to index.php and try and click on the button, you will notice that nothing will happen. The form has been disabled. Open up main.js</p>
<pre name="code" class="javascript">
$('submit_button').disabled = false;
</pre>
<div class="tutorial_image">
<img src="http://nettuts.s3.amazonaws.com/441_mootools/tutorial_img/styled.png" alt="preview" width="600" height="253"/>
</div>
<p>If we add that piece of code in our response.success area, it will enable the button. Simply add it to the reponse.error section, change false to true and give it a test. When the user name is available, you should be able to click the button. When taken, the button should be disabled.</p>
<h3>Step 13 &#8211; The Cleanup</h3>
<p>The user has inserted some text, and then deleted all the text from the input. If you notice all the alerts stay on the screen. This is a bit messy. We should probably fix that. Open main.js.</p>
<pre name="code" class="javascript">
...
The end of our user name event
...

$('user_name').addEvent('blur',function(e){

   	if(this.value == ''){

   		$('user_name').removeClass('success');
   		$('user_name').removeClass('error');
   		$('response').set('html','');

   		$('submit_button').disabled = true;

   	}

   });
</pre>
<p>When the user clicks away from the input, it will fire the event <em>blur</em>. If the input box value is empty, we remove all classes, set the response p to empty and disable the button. Nice and tidy!</p>
<h3>The End</h3>
<p>I hope this tutorial has helped to teach you some of the fundamentals when using simple JSON requests and interacting with elements on the page with Mootools. Feel free to download the source code! If you have any questions, follow me on <a href="http://www.twitter.com/envex">Twitter</a>!</p>
<p>One last note, the button styles used in this tutorial are the property of <a href="http://www.zurb.com/blog_uploads/0000/0485/buttons-02.html" target="_blank">Zurb</a>. Check them out, they do great work!</p>
<ul class="webroundup">
<li>Follow us on <a href="http://www.twitter.com/nettuts">Twitter</a>, or subscribe to the <a href="http://feeds.feedburner.com/nettuts" title="Nettuts+ RSS Feed">Nettuts+ RSS Feed</a> for more daily web development tuts and articles.</li>
</ul>
<p>
<script type="text/javascript"><!--digg_url = "post permalink (not digg url)"; // -->
</script><br />
<script src="http://digg.com/tools/diggthis.js" type="text/javascript"></script></p>
]]></content:encoded>
			<wfw:commentRss>http://net.tutsplus.com/tutorials/javascript-ajax/checking-username-availability-with-mootools-and-request-json/feed/</wfw:commentRss>
		<slash:comments>46</slash:comments>
		</item>
	</channel>
</rss>
<!--
This site's performance optimized by W3 Total Cache:

W3 Total Cache improves the user experience of your blog by caching
frequent operations, reducing the weight of various files and providing
transparent content delivery network integration.

Learn more about our WordPress Plugins: http://www.w3-edge.com/wordpress-plugins/

Page Caching using memcached
Database Caching 14/28 queries in 0.027 seconds using memcached
Content Delivery Network via 

Served from: psdtutsplus.com @ 2009-11-21 07:22:06 -->