http://net.tutsplus.com/tutorials/javascript-ajax/inettuts/

Finished Project

The plan

First, let's list exactly what we'll be creating here and what features it'll have:

  • This interface will contain several widgets.
  • Each widget can be collapsed, removed and edited.
  • The widgets can be sorted into the three seperate columns by the user (using a drag and drop technique).
  • The user will be able to edit the color and title of each widget.
  • Each widget can contain any amount of regular HTML content, text, images, flash etc.

Please note that we will only be covering the front-end aspect of the project in this tutorial. Obviously you could integrate this UI with a solid server-side system which could take care of saving preferences and customised widgets.

Since it's all about the user and because the idea was influenced by iGoogle we're going to be calling this project 'iNettuts'.

The layout of iNettuts

The layout is a simple three column one; each column contains widgets:

layout

Each widget has a "handle" which the user can use to move the widget around.

jQuery UI

As well as the jQuery core library we're also going to make use of the jQuery's UI library and specifically the "sortable" and "draggable" modules. This will make it quite simple to add the drag-and-drop functionality that we want. You should get a personalized download of the UI library which has what we need in it. (Tick the 'sortable' box)

Step 1: XHTML markup

Each column will be an unordered list (UL) and each widget within the columns will be a list item (LI):

First column:

  1. <ul id="column1" class="column">  
  2.   
  3.     <li class="widget red">    
  4.         <div class="widget-head">  
  5.             <h3>Widget title</h3>  
  6.         </div>  
  7.         <div class="widget-content">  
  8.   
  9.             <p>The content...</p>  
  10.         </div>  
  11.     </li>  
  12.     <li class="widget blue">    
  13.         <div class="widget-head">  
  14.   
  15.             <h3>Widget title</h3>  
  16.         </div>  
  17.         <div class="widget-content">  
  18.             <p>The content...</p>  
  19.   
  20.         </div>  
  21.     </li>  
  22. </ul>  

The above code represents the first column, on the left and two widgets each within a list item. As shown in the plan, there will be three columns - three unordered lists.

Step 2: CSS

We'll be using two CSS StyleSheets, one of them will contain all the main styles and the second StyleSheet will only contain styles required by the JavaScript enhancements. The reason we seperate them like this is so that people without JavaScript enabled do not waste their bandwidth downloading styles which they're not going to use.

Here is inettuts.css:

  1. /* Reset */  
  2. body,img,p,h1,h2,h3,h4,h5,h6,ul,ol {margin:0; padding:0; list-style:noneborder:none;}  
  3. /* End Reset */  
  4.       
  5. body {font-size:0.8em; font-family:Arial,Verdana,Sans-Serifbackground#000;}  
  6. a {color:white;}  
  7.       
  8. /* Colours */  
  9. .color-yellow {background:#f2bc00;}  
  10. .color-red    {background:#dd0000;}  
  11. .color-blue   {background:#148ea4;}  
  12. .color-white  {background:#dfdfdf;}  
  13. .color-orange {background:#f66e00;}  
  14. .color-green  {background:#8dc100;}  
  15. .color-yellow h3,.color-white h3,.color-green h3  
  16.     {color:#000;}  
  17. .color-red h3,.color-blue h3,.color-orange h3  
  18.     {color:#FFF;}  
  19. /* End Colours */  
  20.       
  21. /* Head section */  
  22. #head {  
  23.     background#000 url(img/head-bg.png) repeat-x;  
  24.     height100px;  
  25. }  
  26. #head h1 {  
  27.     line-height100px;  
  28.     color#FFF;  
  29.     text-aligncenter;  
  30.     backgroundurl(img/inettuts.png) no-repeat center;  
  31.     text-indent: -9999em  
  32. }  
  33. /* End Head Section */  
  34.       
  35. /* Columns section */  
  36. #columns .column {  
  37.     floatleft;  
  38.     width: 33.3%;  
  39.         /* Min-height: */  
  40.         min-height400px;  
  41.         heightauto !important;   
  42.         height400px;  
  43. }  
  44.       
  45. /* Column dividers (background-images) : */  
  46.     #column#column1 { backgroundurl(img/column-bg-left.png) no-repeat rightright top; }  
  47.     #column#column3 { backgroundurl(img/column-bg-rightright.png) no-repeat left top; }  
  48.           
  49. #column#column1 .widget { margin30px 35px 30px 25px; }  
  50. #column#column3 .widget { margin30px 25px 30px 35px; }  
  51. #columns .widget {  
  52.     margin30px 20px 0 20px;  
  53.     padding2px;  
  54.     -moz-border-radius: 4px;  
  55.     -webkit-border-radius: 4px;  
  56. }  
  57. #columns .widget .widget-head {  
  58.     color#000;  
  59.     overflowhidden;  
  60.     width: 100%;  
  61.     height30px;  
  62.     line-height30px;  
  63. }  
  64. #columns .widget .widget-head h3 {  
  65.     padding: 0 5px;  
  66.     floatleft;  
  67. }  
  68. #columns .widget .widget-content {  
  69.     background#333 url(img/widget-content-bg.png) repeat-x;  
  70.     padding5px;  
  71.     color#DDD;  
  72.     -moz-border-radius-bottomleft: 2px;  
  73.     -moz-border-radius-bottomright: 2px;  
  74.     -webkit-border-bottom-left-radius: 2px;  
  75.     -webkit-border-bottom-rightright-radius: 2px;  
  76.     line-height: 1.2em;  
  77.     overflowhidden;  
  78. }  
  79. /* End Columns section */  

There's nothing too complicated in the above StyleSheet. Normally it would be better to use images instead of the CSS3 border-radius property to create rounded corners (for cross-browser benefits) but they're not really an integral part of the layout - adding a border-radius is quick and painless.

Just a note about the colour classes: Ideally, elements should be named according to their semantic meaning or content, not their appearance. The problem is that the widgets can mean/contain many different things so having classes like this really is the best alternative, unless you're willing to add the colour styles inline. Each colour class is prefixed with 'color-'; it'll become clear why I've done this later in the tutorial.

In the above CSS we're also using a min-height hack for each column so that the background images (the dividers) remain intact and so that an empty column can still have widgets dragged back into it:

  1. #columns .column {  
  2.     floatleft;  
  3.     width: 33.3%;  
  4.       
  5.     /* Min-height: */  
  6.         min-height400px;  
  7.         heightauto !important;   
  8.         height400px;  
  9. }  

We'll focus on the second stylesheet later when we've added the JavaScript.

Here's a preview of what we've got so far, just CSS/HTML (and some images):

layout

Step 3: JavaScript

Introduction

As I've said, we'll be using jQuery. It's the library of choice not only because of the UI modules it offers but also because it will help in speeding up the development process while keeping everything cross-browser operable.

The final product will have endless possibilities, some of which have already been explored by the likes of NetVibes and iGoogle. So, we want to make sure our code is easily maintainable, allows for expandability and is reusable; we want it to be future-proof!

We'll begin with a global object called "iNettuts" - this will act as the sole occupied namespace of the project (plus dependencies such as jQuery). Under it we will code up the main functionality of the site which utilises jQuery and its UI library.

inettuts.js:

  1. var iNettuts = {  
  2.     settings : {  
  3.        // Some simple settings will go here.  
  4.     },  
  5.     init : function(){  
  6.         // The method which starts it all...  
  7.     }  
  8. };  

The init method will be called when the document is ready for manipulation (i.e. when the DOM is loaded and ready). While there are various methods available it has been proven that the quickest way to initialise your code upon this event is to call it from the bottom of your document. It also makes sense to link to all the scripts at the bottom so as not to slow down the loading of the rest of the page:

  1. <body>  
  2.       
  3.     <!-- page content -->  
  4.   
  5.       
  6.       
  7.     <!-- Bottom of document -->  
  8.     <script type="text/javascript" src="http://jqueryjs.googlecode.com/files/jquery-1.2.6.min.js"></script>  
  9.     <script type="text/javascript" src="inettuts.js"></script>  
  10.   
  11.     <script type="text/javascript" src="jquery-ui-personalized-1.6rc2.min.js"></script>  
  12.       
  13. </body>  

Settings

As I've said, there will be a settings object which will contain all of the global settings required to make this functional. We'll also have individual widget settings objects, this means it will be possible to create per-widget settings.

settings object (under iNettuts):

  1. settings : {  
  2.     /* Specify selectors */  
  3.     columns : '.column',  
  4.     widgetSelector: '.widget',  
  5.     handleSelector: '.widget-head',  
  6.     contentSelector: '.widget-content',  
  7.     /* Settings for the Widgets: */  
  8.     widgetDefault : {  
  9.         movable: true,  
  10.         removable: true,  
  11.         collapsible: true,  
  12.         editable: true,  
  13.         colorClasses : ['yellow','red','blue','white','orange','green']  
  14.     },  
  15.     /* Individual Widget settings: */  
  16.     widgetIndividual : {  
  17.         intro : {  
  18.             movable: false,  
  19.             removable: false,  
  20.             collapsible: false  
  21.         },  
  22.         gallery : {  
  23.             colorClasses : ['yellow','red','white']  
  24.         }  
  25.     }  
  26. }  

Yes, there are quite a lot of settings, but if we want maximum code reusability this is a necessity. Most of the above is self explanatory. As you can see we've setup a widgetDefault object which contains the default settings for each widget; if you want to override these settings then the script will require you to give the widget an id (in the HTML) and then create a new ruleset. We've got two rule-sets (objects) which override their defaults, 'intro' and 'gallery'. So, those rules specified in the "gallery" object will only apply to this widget:

  1. <li class="widget blue" id="gallery">    
  2.     <div class="widget-head">  
  3.         <h3>Instructions</h3>  
  4.     </div>  
  5.   
  6.     <div class="widget-content">  
  7.         <ul>  
  8.             <li>To move a widget...</li>  
  9.         </ul>  
  10.     </div>  
  11.   
  12. </li>  

Retrieving the settings

getWidgetSettings object (under iNettuts):

  1. getWidgetSettings : function(id) {  
  2.     var settings = this.settings;  
  3.     return (id&&settings.widgetIndividual[id]) ?   
  4.         $.extend({},settings.widgetDefault,settings.widgetIndividual[id])  
  5.         : settings.widgetDefault;  
  6. }  

This method will return an object with the settings of any particular widget. If a widget has no id (HTML attribute) then it will just return the default settings, otherwise it will look to see if that widget has settings of its own, if it does then it will return the default settings and that widget's settings merged into a single object (the widget's individual settings have precedence).

Attaching a CSS file using JavaScript

I mentioned earlier that we have an additional stylesheet which the JavaScript enhancements will require.

Here's the StyleSheet (inettuts.js.css):

  1. /* JS-Enabled CSS */  
  2.       
  3. .widget-head a.remove  {  
  4.     floatrightright;  
  5.     displayinline;  
  6.     backgroundurl(img/buttons.gif) no-repeat -24px 0;  
  7.     width14px;  
  8.     height14px;  
  9.     margin8px 4px 8px 0;  
  10.     text-indent: -9999em;  
  11.     outlinenone;  
  12. }  
  13.       
  14. .widget-head a.edit  {  
  15.     floatrightright;  
  16.     displayinline;  
  17.     backgroundurl(img/buttons.gif) no-repeat;  
  18.     width24px;  
  19.     height14px;  
  20.     text-indent: -9999em;  
  21.     margin8px 4px 8px 4px;  
  22.     outlinenone;  
  23. }  
  24.       
  25. .widget-head a.collapse  {  
  26.     floatleft;  
  27.     displayinline;  
  28.     backgroundurl(img/buttons.gif) no-repeat -52px 0;  
  29.     width14px;  
  30.     height14px;  
  31.     text-indent: -9999em;  
  32.     margin8px 0 8px 4px;  
  33.     outlinenone;  
  34. }  
  35.       
  36. .widget-placeholder { border2px dashed #999;}  
  37. #column1 .widget-placeholder { margin30px 35px 0 25px; }  
  38. #column2 .widget-placeholder { margin30px 20px 0 20px; }  
  39. #column3 .widget-placeholder { margin30px 25px 0 35px; }  
  40.       
  41. .edit-box {  
  42.     overflowhidden;  
  43.     background#333 url(img/widget-content-bg.png) repeat-x;  
  44.     margin-bottom2px;  
  45.     padding10px 0;  
  46. }  
  47.       
  48. .edit-box li.item {  
  49.     padding10px 0;  
  50.     overflowhidden;  
  51.     floatleft;  
  52.     width: 100%;  
  53.     clearboth;  
  54. }  
  55.       
  56. .edit-box label {  
  57.     floatleft;  
  58.     width: 30%;  
  59.     color#FFF;  
  60.     padding: 0 0 0 10px;  
  61. }  
  62.       
  63. .edit-box ul.colors li {  
  64.     width20px;  
  65.     height20px;  
  66.     border1px solid #EEE;  
  67.     floatleft;  
  68.     displayinline;  
  69.     margin: 0 5px 0 0;  
  70.     cursorpointer;  
  71. }  

The elements targetted in the above StyleSheet have yet to be coded, but eventually we will write the JavaScript which dynamically adds these elements to the page, thus making use of the StyleSheet.

The method which attaches this StyleSheet is called 'attachStylesheet':

  1. attachStylesheet : function (href) {  
  2.     return $('<link href="' + href + '" rel="stylesheet" type="text/css" />').appendTo('head');  
  3. }  

The above method appends a link to the head of the document. When a new link element is added to the document through the DOM the browser will load it and apply its CSS rules as it would for any regular hard-coded linked StyleSheet. When doing this, remember that the rules of CSS inheritance and specificity still apply.

Making the widgets work

Widgets

The next part of the tutorial is probably the hardest, so take it slowly.

We want to add another method to our global iNettuts object, we'll call it makeSortable:

  1. makeSortable : function () {  
  2.     // This function will make the widgets 'sortable'!  
  3. }  

By the way, 'method' is just a fancy name given to 'functions' which have been assigned to object properties. In this case our object is called 'iNettuts' so 'makeSortable' is a method of 'iNettuts'...

This new method will take the settings we specified in the 'settings' object and make the required element sortable.

First, we want to make sure everything we need is easily accessible within this new method:

  1. makeSortable : function () {  
  2.     var iNettuts = this// *1  
  3.         $ = this.jQuery, // *2  
  4.         settings = this.settings; // *3  
  5. }  

*1: There will only be one instance of our global object, but just encase multiple instances need to be made or if we want to rename the global object it's a good idea to set a new variable (in this case 'iNettuts') to the 'this' keyword which references the object that this method is within. Be careful, the 'this' keyword is a bit of a beast and doesn't always reference what you think it does!

*2: At the very top of the iNettuts object we've placed a new property: 'jQuery : $'. In the pursuit of maximum code reusability we don't want our script to conflict with any other libraries that also make use of the dollar-sign symbol (e.g. The Prototype library). So, for example, if you renamed jQuery to JQLIB then you could change the 'jQuery' property to JQLIB and the script would continue to function properly. The 2nd line in the above code isn't necessary at all, - if we didn't want it we could just use this.jQuery().ajQueryFunction() instead of $() within this method.

*3: Again, this isn't really necessary, we're just creating a bit of a shortcut, so instead of having to type out 'this.settings' within this method we only need to type out 'settings'.

The next step is to define a set of sortable items (i.e. the widgets that will be movable). Remember, back in the settings we made it possible to set a property called 'movable' to true or false. If 'movable' is set to false, either by default or on individual widgets we have to cater for that:

  1. /* 
  2.  * (using the dollar prefix on $sortableItems is a convention when a variable references a jQuery object) 
  3.  */  
  4.     
  5. $sortableItems = (function () {  
  6.       
  7.     // Define an empty string which can add to within the loop:  
  8.     var notSortable = '';  
  9.       
  10.     // Loop through each widget within the columns:  
  11.     $(settings.widgetSelector,$(settings.columns)).each(function (i) {  
  12.           
  13.         // If the 'movable' property is set to false:  
  14.         if (!iNettuts.getWidgetSettings(this.id).movable) {  
  15.               
  16.             // If this widget has NO ID:   
  17.             if(!this.id) {  
  18.                   
  19.                 // Give it an automatically generated ID:  
  20.                 this.id = 'widget-no-id-' + i;  
  21.                   
  22.             }  
  23.           
  24.             // Add the ID to the 'notSortable' string:  
  25.             notSortable += '#' + this.id + ',';  
  26.         }  
  27.           
  28.     });  
  29.       
  30.     /* 
  31.     * This function will return a jQuery object containing 
  32.     * those widgets which are movable. 
  33.     */  
  34.     return $('> li:not(' + notSortable + ')', settings.columns);  
  35. })();  

Now we've got a set of DOM elements referenced in the jQuery object which is returned from the above functions. We can make immediate use of this:

  1. $sortableItems.find(settings.handleSelector).css({  
  2.     cursor: 'move'  
  3. }).mousedown(function (e) {  
  4.     $(this).parent().css({  
  5.         width: $(this).parent().width() + 'px'  
  6.     });  
  7. }).mouseup(function () {  
  8.     if(!$(this).parent().hasClass('dragging')) {  
  9.         $(this).parent().css({width:''});  
  10.     }  
  11. });  

So, we're looking for what has been defined as the 'handle' within the movable widgets (within sortableItems) and then we're applying a new CSS cursor property of 'move' to each one; this is to make it obvious that each widget is movable.

The mousedown and mouseup functions are needed to work around some issues with dragging and dropping... Since we want this page and all the elements inside it to expand when the browser is resized we haven't set any explicit widths on the widgets (list items). When one of these list items is being sorted it becomes absolutely positioned (while being dragged) which means that it will stretch to its content's composite width. Here's an example:

When dragged the widget stretches to length of page

This is what should be happening:

When dragged the widget has the correct width!

To make this happen we have explicitly set the widget's width to what it was before dragging had begun. The UI 'sortable' module does have a property in which you can put a function that will run when a widget starts being sorted (i.e. when it starts being dragged), unfortunately this is not good enough for us because it runs too late; we need to set the width before the 'sortable' module takes hold - the best way to do this is by running a function on mousedown of the handle (the 'handle', in this case, is the bar at the top of each widget).

  1. // mousedown function:  
  2. // Traverse to parent (the widget):  
  3. $(this).parent().css({  
  4.     // Explicitely set width as computed width:  
  5.     width: $(this).parent().width() + 'px'  
  6. });  

If we leave it like this then when you drop the widget in a certain place and res

the browser the widget will not change in size. In order to prevent this we need to write a function to be tied to the mouseup event of the handle:

  1. // mouseup function:  
  2. // Check if widget is currently in the process of dragging:  
  3. if(!$(this).parent().hasClass('dragging')) {  
  4.     // If it's not then reset width to '':  
  5.     $(this).parent().css({width:''}); 
  6. } else { 
  7.     // If it IS currently being dragged then we want to  
  8.     // temporarily disable dragging, while widget is 
  9.     // reverting to original position. 
  10.     $(settings.columns).sortable('disable');  
  11. }  

The 'dragging' class is added on that 'start' property of the sortable module which we talked about earlier. (we'll write that code later)

This is what our makeSortable method looks like so far:

  1. makeSortable : function () {  
  2.     var iNettuts = this,  
  3.         $ = this.jQuery,  
  4.         settings = this.settings,  
  5.           
  6.         $sortableItems = (function () {  
  7.             var notSortable = '';  
  8.             $(settings.widgetSelector,$(settings.columns)).each(function (i) {  
  9.                 if (!iNettuts.getWidgetSettings(this.id).movable) {  
  10.                     if(!this.id) {  
  11.                         this.id = 'widget-no-id-' + i;  
  12.                     }  
  13.                     notSortable += '#' + this.id + ',';  
  14.                 }  
  15.             });  
  16.             return $('> li:not(' + notSortable + ')', settings.columns);  
  17.         })();  
  18.       
  19.     $sortableItems.find(settings.handleSelector).css({  
  20.         cursor: 'move'  
  21.     }).mousedown(function (e) {  
  22.         $sortableItems.css({width:''});  
  23.         $(this).parent().css({  
  24.             width: $(this).parent().width() + 'px'  
  25.         });  
  26.     }).mouseup(function () {  
  27.         if(!$(this).parent().hasClass('dragging')) {  
  28.             $(this).parent().css({width:''});  
  29.         } else {  
  30.             $(settings.columns).sortable('disable');  
  31.         }  
  32.     });  
  33. }  

Next, still within 'makeSortable' we need to initialise the 'sortable' module:

  1. makeSortable : function () {  
  2.     // ...........................  
  3.     // BEGINNING OF METHOD (above)  
  4.     // ...........................  
  5.       
  6.     // Select the columns and initiate 'sortable':  
  7.     $(settings.columns).sortable({  
  8.       
  9.         // Specify those items which will be sortable:  
  10.         items: $sortableItems,  
  11.           
  12.         // Connect each column with every other column:  
  13.         connectWith: $(settings.columns),  
  14.           
  15.         // Set the handle to the top bar:  
  16.         handle: settings.handleSelector,  
  17.           
  18.         // Define class of placeholder (styled in inettuts.js.css)  
  19.         placeholder: 'widget-placeholder',  
  20.           
  21.         // Make sure placeholder size is retained:  
  22.         forcePlaceholderSize: true,  
  23.           
  24.         // Animated revent lasts how long?  
  25.         revert: 300,  
  26.           
  27.         // Delay before action:  
  28.         delay: 100,  
  29.           
  30.         // Opacity of 'helper' (the thing that's dragged):  
  31.         opacity: 0.8,  
  32.           
  33.         // Set constraint of dragging to the document's edge:  
  34.         containment: 'document',  
  35.           
  36.         // Function to be called when dragging starts:  
  37.         start: function (e,ui) {  
  38.             $(ui.helper).addClass('dragging');  
  39.         },  
  40.           
  41.         // Function to be called when dragging stops:  
  42.         stop: function (e,ui) {  
  43.           
  44.             // Reset width of units and remove dragging class:  
  45.             $(ui.item).css({width:''}).removeClass('dragging');  
  46.               
  47.             // Re-enable sorting (we disabled it on mouseup of the handle):  
  48.             $(settings.columns).sortable('enable');  
  49.               
  50.         }  
  51.           
  52.     });  
  53.       
  54. }  

The above options setup the behaviour we want for our sortable widgets. There are plenty more available options for this module but those above will be sufficient for now.

Editing, removing and collapsing widgets

The next step is to make it possible for the user to collapse widgets, close (remove) widgets and edit certain elements within each widget.

We're going to put this all within one method, we'll call it 'addWidgetControls':

  1. addWidgetControls : function () {  
  2.     // This function will add controls to each widget!  
  3. }  

As with 'makeSortable' we want to set the following variables at the start:

  1. addWidgetControls : function () {  
  2.     var iNettuts = this,  
  3.         $ = this.jQuery,  
  4.         settings = this.settings;  
  5. }  

We need to loop through every widget on the page and add functionality dependent on the default settings or the settings made for any particular widget.

  1. // Loop through each widget:  
  2. $(settings.widgetSelector, $(settings.columns)).each(function () {  
  3.   
  4.     /* Merge individual settings with default widget settings */  
  5.     var thisWidgetSettings = iNettuts.getWidgetSettings(this.id);  
  6.       
  7.     // (if "removable" option is TRUE):  
  8.     if (thisWidgetSettings.removable) {  
  9.       
  10.         // Add CLOSE (REMOVE) button & functionality  
  11.           
  12.     }  
  13.       
  14.     // (if "removable" option is TRUE):  
  15.     if (thisWidgetSettings.editable) {  
  16.       
  17.         // Add EDIT button and functionality  
  18.           
  19.     }  
  20.       
  21.     // (if "removable" option is TRUE):  
  22.     if (thisWidgetSettings.collapsible) {  
  23.       
  24.         // Add COLLAPSE button and functionality  
  25.           
  26.     }  
  27.           
  28. });  

As you can see from the above code, we're checking the settings before adding any one of the three buttons and each button’s corresponding functionality.

Before we write out exactly what will happen within each of three conditions let's list exactly what each of these buttons will do:

  • CLOSE (remove): This button will remove the widget from the DOM. Instead of just removing it immediately we'll apply an effect which will fade out he widget and then slide up its occupied space.
  • EDIT: This button, when clicked, will bring up an 'edit box' section within the widget. Within this 'edit' section the user can change the title of the widget and its colour. To close the 'edit' section the user must click on the same 'edit' button again - so basically this button toggles the 'edit' section.
  • COLLAPSE: This button switches between an up-arrow and a down-arrow dependent whether the widget is collapsed or not. Collapsing a widget will simply hide its content, so the only viewable of the widget will be the handle (the bar at the top of each widget).

We know what we want now, so we can start writing it: (The snippets below are riddles with comments so make sure you read through the code!)

CLOSE (remove):

  1. // (if "removable" option is TRUE):  
  2. if (thisWidgetSettings.removable) {  
  3.       
  4.     // Create new anchor element with class of 'remove':  
  5.     $('<a href="#" class="remove">CLOSE</a>').mousedown(function (e) {  
  6.       
  7.         // Stop event bubbling:  
  8.         e.stopPropagation();   
  9.              
  10.     }).click(function () {  
  11.       
  12.         // Confirm action - make sure that the user is sure:  
  13.         if(confirm('This widget will be removed, ok?')) {  
  14.           
  15.             // Animate widget to an opacity of 0:  
  16.             $(this).parents(settings.widgetSelector).animate({  
  17.                 opacity: 0      
  18.             },function () {  
  19.               
  20.                 // When animation (opacity) has finished:  
  21.                 // Wrap in DIV (explained below) and slide up:  
  22.                 $(this).wrap('<div/>').parent().slideUp(function () {  
  23.                   
  24.                     // When sliding up has finished, remove widget from DOM:  
  25.                     $(this).remove();  
  26.                       
  27.                 });  
  28.             });  
  29.         }  
  30.           
  31.         // Return false, prevent default action:  
  32.         return false;  
  33.           
  34.     })  
  35.       
  36.     // Now, append the new button to the widget handle:  
  37.     .appendTo($(settings.handleSelector, this));  
  38.       
  39. }  

EDIT:

  1. /* (if "editable" option is TRUE) */  
  2. if (thisWidgetSettings.editable) {  
  3.       
  4.     // Create new anchor element with class of 'edit':  
  5.     $('<a href="#" class="edit">EDIT</a>').mousedown(function (e) {  
  6.           
  7.         // Stop event bubbling  
  8.         e.stopPropagation();  
  9.           
  10.     }).toggle(function () {  
  11.         // Toggle: (1st state):  
  12.           
  13.         // Change background image so the button now reads 'close edit':  
  14.         $(this).css({backgroundPosition: '-66px 0', width: '55px'})  
  15.               
  16.             // Traverse to widget (list item):  
  17.             .parents(settings.widgetSelector)  
  18.                   
  19.                 // Find the edit-box, show it, then focus <input/>:  
  20.                 .find('.edit-box').show().find('input').focus();  
  21.                   
  22.         // Return false, prevent default action:  
  23.         return false;  
  24.           
  25.     },function () {  
  26.         // Toggle: (2nd state):  
  27.           
  28.         // Reset background and width (will default to CSS specified in StyleSheet):  
  29.         $(this).css({backgroundPosition: '', width: ''})  
  30.               
  31.             // Traverse to widget (list item):  
  32.             .parents(settings.widgetSelector)  
  33.                   
  34.                 // Find the edit-box and hide it:  
  35.                 .find('.edit-box').hide();  
  36.         // Return false, prevent default action:  
  37.         return false;  
  38.   
  39.     })  
  40.       
  41.     // Append this button to the widget handle:  
  42.     .appendTo($(settings.handleSelector,this));  
  43.       
  44.     // Add the actual editing section (edit-box):  
  45.     $('<div class="edit-box" style="display:none;"/>')  
  46.         .append('<ul><li class="item"><label>Change the title?</label><input value="' + $('h3',this).text() + '"/></li>')  
  47.         .append((function(){  
  48.               
  49.             // Compile list of available colours:  
  50.             var colorList = '<li class="item"><label>Available colors:</label><ul class="colors">';  
  51.               
  52.             // Loop through available colors - add a list item for each:  
  53.             $(thisWidgetSettings.colorClasses).each(function () {  
  54.                 colorList += '<li class="' + this + '"/>';  
  55.             });  
  56.               
  57.             // Return (to append function) the entire colour list:  
  58.             return colorList + '</ul>';  
  59.               
  60.         })())  
  61.           
  62.         // Finish off list:  
  63.         .append('</ul>')  
  64.           
  65.         // Insert the edit-box below the widget handle:  
  66.         .insertAfter($(settings.handleSelector,this));  
  67.           
  68. }  

COLLAPSE:

  1. // (if 'collapsible' option is TRUE)   
  2. if (thisWidgetSettings.collapsible) {  
  3.       
  4.     // Create new anchor with a class of 'collapse':  
  5.     $('<a href="#" class="collapse">COLLAPSE</a>').mousedown(function (e) {  
  6.           
  7.         // Stop event bubbling:  
  8.         e.stopPropagation();  
  9.           
  10.   
  11.     }).toggle(function () {  
  12.         // Toggle: (1st State):  
  13.           
  14.         // Change background (up-arrow to down-arrow):  
  15.         $(this).css({backgroundPosition: '-38px 0'})  
  16.           
  17.             // Traverse to widget (list item):  
  18.             .parents(settings.widgetSelector)  
  19.                 // Find content within widget and HIDE it:  
  20.                 .find(settings.contentSelector).hide();  
  21.                   
  22.         // Return false, prevent default action:  
  23.         return false;  
  24.           
  25.     },function () {  
  26.         // Toggle: (2nd State):  
  27.           
  28.         // Change background (up-arrow to down-arrow):  
  29.         $(this).css({backgroundPosition: ''})  
  30.           
  31.             // Traverse to widget (list item):  
  32.             .parents(settings.widgetSelector)  
  33.               
  34.                 // Find content within widget and SHOW it:  
  35.                 .find(settings.contentSelector).show();  
  36.                   
  37.         // Return false, prevent default action:  
  38.         return false;  
  39.           
  40.     })  
  41.       
  42.     // Prepend that 'collapse' button to the widget's handle:  
  43.     .prependTo($(settings.handleSelector,this));  
  44. }  

What is "Event Bubbling"?

Event bubbling or 'propagation' is when, upon clicking on an element, the event will bubble up through the DOM to the highest level element with an event the same as the event you just triggered on the original element. If we didn't stop propogation in the above snippets (e.stopPropagation();) on the mouseDown event of each added button then the mouseDown event of the handle (parent of the buttons) would also trigger and thus the dragging would would begin just by holding your mouse down over one of the buttons - we don't want this to happen; we only want dragging to begin when the user puts their mouse directly over the handle and pushes down.

Edit-box events/functionality

We've written the code which will inject the edit boxes into the document in the correct places. - We added an input box so users can change the title of a widget and we also added a list of available colours. So, we now need to loop through each new edit-box (hidden from view) and specify how these elements can be interacted with:

  1. // Loop through each edit-box (under each widget that has an edit-box)  
  2. $('.edit-box').each(function () {  
  3.       
  4.     // Assign a function to the onKeyUp event of the input:  
  5.     $('input',this).keyup(function () {  
  6.           
  7.         // Traverse UP to widget and find the title, set text to  
  8.         // the input element's value - if the value is longer  
  9.         // than 20 characters then replace remainder characters  
  10.         // with an elipsis (...).  
  11.         $(this).parents(settings.widgetSelector).find('h3').text( $(this).val().length>20 ? $(this).val().substr(0,20)+'...' : $(this).val() ); 
  12.          
  13.     }); 
  14.      
  15.     // Assing a function to the Click event of each colour list-item: 
  16.     $('ul.colors li',this).click(function () { 
  17.          
  18.         // Define colorStylePattern to match a class with prefix 'color-': 
  19.         var colorStylePattern = /\bcolor-[\w]{1,}\b/, 
  20.              
  21.             // Define thisWidgetColorClass as the colour class of the widget: 
  22.             thisWidgetColorClass = $(this).parents(settings.widgetSelector).attr('class').match(colorStylePattern) 
  23.         // If a class matching the pattern does exist: 
  24.         if (thisWidgetColorClass) { 
  25.              
  26.             // Traverse to widget: 
  27.             $(this).parents(settings.widgetSelector) 
  28.              
  29.                 // Remove the old colour class: 
  30.                 .removeClass(thisWidgetColorClass[0]) 
  31.                  
  32.                 // Add new colour class (n.b. 'this' refers to clicked list item): 
  33.                 .addClass($(this).attr('class').match(colorStylePattern)[0]);  
  34.                   
  35.         }  
  36.           
  37.         // Return false, prevent default action:  
  38.         return false;  
  39.           
  40.     });  
  41. });  

The edit-boxes are entirely functional now. All the above code resides in the 'addWidgetControls' method.

  1. addWidgetControls : function () {  
  2.     var iNettuts = this,  
  3.         $ = this.jQuery,  
  4.         settings = this.settings;  
  5.           
  6.     $(settings.widgetSelector, $(settings.columns)).each(function () {  
  7.         var thisWidgetSettings = iNettuts.getWidgetSettings(this.id);  
  8.           
  9.         if (thisWidgetSettings.removable) {  
  10.             $('<a href="#" class="remove">CLOSE</a>').mousedown(function (e) {  
  11.                 e.stopPropagation();      
  12.             }).click(function () {  
  13.                 if(confirm('This widget will be removed, ok?')) {  
  14.                     $(this).parents(settings.widgetSelector).animate({  
  15.                         opacity: 0      
  16.                     },function () {  
  17.                         $(this).wrap('<div/>').parent().slideUp(function () {  
  18.                             $(this).remove();  
  19.                         });  
  20.                     });  
  21.                 }  
  22.                 return false;  
  23.             }).appendTo($(settings.handleSelector, this));  
  24.         }  
  25.           
  26.         if (thisWidgetSettings.editable) {  
  27.             $('<a href="#" class="edit">EDIT</a>').mousedown(function (e) {  
  28.                 e.stopPropagation();      
  29.             }).toggle(function () {  
  30.                 $(this).css({backgroundPosition: '-66px 0', width: '55px'})  
  31.                     .parents(settings.widgetSelector)  
  32.                         .find('.edit-box').show().find('input').focus();  
  33.                 return false;  
  34.             },function () {  
  35.                 $(this).css({backgroundPosition: '', width: ''})  
  36.                     .parents(settings.widgetSelector)  
  37.                         .find('.edit-box').hide();  
  38.                 return false;  
  39.             }).appendTo($(settings.handleSelector,this));  
  40.             $('<div class="edit-box" style="display:none;"/>')  
  41.                 .append('<ul><li class="item"><label>Change the title?</label><input value="' + $('h3',this).text() + '"/></li>')  
  42.                 .append((function(){  
  43.                     var colorList = '<li class="item"><label>Available colors:</label><ul class="colors">';  
  44.                     $(thisWidgetSettings.colorClasses).each(function () {  
  45.                         colorList += '<li class="' + this + '"/>';  
  46.                     });  
  47.                     return colorList + '</ul>';  
  48.                 })())  
  49.                 .append('</ul>')  
  50.                 .insertAfter($(settings.handleSelector,this));  
  51.         }  
  52.           
  53.         if (thisWidgetSettings.collapsible) {  
  54.             $('<a href="#" class="collapse">COLLAPSE</a>').mousedown(function (e) {  
  55.                 e.stopPropagation();      
  56.             }).toggle(function () {  
  57.                 $(this).css({backgroundPosition: '-38px 0'})  
  58.                     .parents(settings.widgetSelector)  
  59.                         .find(settings.contentSelector).hide();  
  60.                 return false;  
  61.             },function () {  
  62.                 $(this).css({backgroundPosition: ''})  
  63.                     .parents(settings.widgetSelector)  
  64.                         .find(settings.contentSelector).show();  
  65.                 return false;  
  66.             }).prependTo($(settings.handleSelector,this));  
  67.         }  
  68.     });  
  69.       
  70.     $('.edit-box').each(function () {  
  71.         $('input',this).keyup(function () {  
  72.             $(this).parents(settings.widgetSelector).find('h3').text( $(this).val().length>20 ? $(this).val().substr(0,20)+'...' : $(this).val() );  
  73.         });  
  74.         $('ul.colors li',this).click(function () {  
  75.               
  76.             var colorStylePattern = /\bcolor-[\w]{1,}\b/,  
  77.                 thisWidgetColorClass = $(this).parents(settings.widgetSelector).attr('class').match(colorStylePattern)  
  78.             if (thisWidgetColorClass) {  
  79.                 $(this).parents(settings.widgetSelector)  
  80.                     .removeClass(thisWidgetColorClass[0])  
  81.                     .addClass($(this).attr('class').match(colorStylePattern)[0]);  
  82.             }  
  83.             return false;  
  84.               
  85.         });  
  86.     });  
  87.       
  88. }  

Almost finished

Now that we've written most of the JavaScript we can write the initiating method and intialise the script!

  1. // Additional method within 'iNettuts' object:  
  2. init : function () {  
  3.     this.attachStylesheet('inettuts.js.css');  
  4.     this.addWidgetControls();  
  5.     this.makeSortable();  
  6. }  

Now, to start it all:

  1. // Right at the very end of inettuts.js  
  2. iNettuts.init();  

Just so we're clear, this is the overall structure of our iNettuts object with each of its methods explained:

  1. var iNettuts = {  
  2.       
  3.     /* Set's jQuery identifier: */  
  4.     jQuery : $,  
  5.       
  6.     settings : {  
  7.           
  8.         /*    Name : settings 
  9.          *    Type : Object 
  10.          * Purpose : Object to store preferences for widget behaviour 
  11.          */  
  12.            
  13.     },  
  14.   
  15.     init : function () {  
  16.           
  17.         /*    Name : init 
  18.          *    Type : Function 
  19.          * Purpose : Initialise methods to be run when page has loaded. 
  20.          */  
  21.            
  22.     },  
  23.       
  24.     getWidgetSettings : function (id) {  
  25.           
  26.         /*      Name : getWidgetSettings 
  27.          *      Type : Function 
  28.          * Parameter : id of widget 
  29.          *   Purpose : Get default and per-widget settings specified in  
  30.          *             the settings object and return a new object 
  31.          *             combining the two, giving per-widget settings 
  32.          *             precedence obviously. 
  33.          */  
  34.            
  35.     },  
  36.       
  37.     addWidgetControls : function () {  
  38.           
  39.         /*    Name : settings 
  40.          *    Type : Function 
  41.          * Purpose : Adds controls (e.g. 'X' close button) to each widget. 
  42.          */  
  43.            
  44.     },  
  45.       
  46.     attachStylesheet : function (href) {  
  47.           
  48.         /*      Name : settings 
  49.          *      Type : Function 
  50.          * Parameter : href location of stylesheet to be added 
  51.          *   Purpose : Creates new link element with specified href and  
  52.          *             appends to <head> 
  53.          */  
  54.            
  55.     },  
  56.       
  57.     makeSortable : function () {  
  58.           
  59.         /*    Name : settings 
  60.          *    Type : Function 
  61.          * Purpose : Makes widgets sortable (draggable/droppable) using 
  62.          *           the jQuery UI 'sortable' module. 
  63.          */  
  64.            
  65.     }  
  66.     
  67. };  

 Finished!

Finished Project

We're totally finished, the interface should be totally operable now. I've tested it on my PC (running Windows XP) in the following browsers: Firefox 2, Firefox 3, Opera 9.5, Safari 3, IE6, IE7 & Chrome.

Note: There are a couple of issues in IE. Specifically, it doesn't set the placeholder size correctly plus there are some CSS issues in IE6 (to be expected).

At first glance this interface's potential applications seem limited to those like iGoogle or NetVibes but it can, in fact, be used for many different things.

  • You could, for example use it on your blog by giving the user the option to sort your blog's widgets in the sidebar - you could then save their preference to a cookie so that the widgets would be in the same order when the user returns.
  • If you add a user authentication system and a database then you've got yourself a simple iGoogle.
  • The 'sortable' plugin itself can be used for sorting any elements, they don't have to be widgets.

Regardless of whether you're going to use this in a project or not I hope you've learnt something today!


by Anna 안나 2009. 3. 1. 00:20