Wednesday, March 25, 2009

Using jQuery Manipulation Functions (Append, Prepend, After, Before) To Reorder Items

I discovered something interesting quite by accident today. I was trying to figure out the best way to reorder certain <li> items based on the value of a particular trait (while ignoring those <li> items that didn't have that particular trait at all). I figured the best way to accomplish this was to:

  1. Select all of the items that had the trait and store them in an array
  2. Resort the contents of the array into a new array.
  3. Delete the selected items from the list (so as not to replicate them)
  4. Loop through the new array and add the items back into the list using the jQuery prepend() function to put them at the top of the list.

When I ran my first test of my code, I left out the deletion step so I could compare the original item order with the new item order, figuring I would have duplicates of the selected items.

However, I was surprised to discover that prepend() removed the original instances of the selected list items, leaving only the prepended copies. Essentially, it ended up moving the items rather than duplicating them.

There's nothing on the official documentation page that says that if you're prepending an item to a collection that already contains an instance of that item that it will remove the original item for you, but that's apparently what it's programmed to do.

I ran a quick test of some of the other related Manipulation functions (append(),after(),before()), and they all seem to behave that way as well.

Thought it was worth sharing. Certainly makes my reordering task a bit easier.

Friday, March 20, 2009

Using jQuery UI Sortables To Move Items From One List To Another

During my most recent project, my clients asked me to build a web-based tool that would help them place volunteers into various standing committees. Placements would be made based on the preferences of the volunteers (who were asked to choose up to three committees they would like to serve on), the vacancies created in each committee by outgoing members, and the desire to have a diversity of units and divisions represented in each committee.

I decided pretty quickly that the most natural way to represent this placement process on a web page would be to let them "physically" move a volunteer into a committee. I had built similar tools before (even before I started using jQuery), but never with more than two lists or collections, so I went to the jQuery UI site to see what my options were.

I started with the most obvious place to start, the Droppable interaction, but soon realized that a better choice for this task was the Sortables interaction.

The primary focus of the Sortable interaction is to let you reorder a collection of DOM elements by dragging them up-and-down through the collection. It's extremely easy to implement in its most basic form. If you wanted to make all of the <li> elements in a <ul> with an "id" attribute "listA" sortable, you can do it in one line:

$(document).ready() {
  $("#listA").sortable();
});

...you can see that code in action on the home page of the Sortables interaction.

What I discovered was that it was almost as easy to connect one Sortable list to another, so that in addition to being able to move reorder items within each list, you could drag items from one list to the other, simply by using the "connectWith" option:

$(document).ready() {
  $("#listA").sortable({
    connectWith: ['#listB']
   });

$("#listB").sortable({
   connectWith: ['#listA']
  });

});

...In the code above, the first sortable() function call makes listA sortable and uses the "connectWith" option to allow items from listA to be dragged into listB. The second sortable() function call lets you sort items in listB and drag items from listB over to listA (even items that originally belonged to listA). If you wanted the movement to only go in one direction (from listA to listB but not back again), you could leave out the "connectWith" option for listB.

Again, the jQuery UI site has a nice ready-made demo of this.

All well and good, but right now all this code does is create the visual effect of moving an item from one list to another. Actually recording the fact that a particular item was moved from one list to the other requires more code, code that is invoked whenever such a move takes place. Being the smart guys and gals that they are, the jQuery UI team built a couple of custom events into the Sortables interaction so you can run additional functions when a certain event has taken place. For my purposes, I only needed to utilize two of these events: receive and remove:

$(document).ready({
  $("#listB").sortable({
    connectWith: ['#listA'],
    receive: function(event, ui) {
       //Run this code whenever an item is dragged and dropped into this list 
       var itemText= ui.item.text();
alert(itemText + " just joined this list");
}, remove: function(event, ui){ //Run this code whenever an item is dragged and dropped out of this list var itemText= ui.item.text(); alert(itemText + " just left this list"); } }); });

...The code is, for the most part, self-explanatory, save for one line (repeated twice): var itemText= ui.item.text()

The ui object is a "prepared" object created by jQuery UI that holds a number of objects and data associated with the event that just took place. The item object within the ui object represents the item that was moved in or out of the list, so I can treat it as a jQuery object and retrieve the text of the item using the standard text() function. You can find a full list of the data contained in the ui object by clicking on the "Overview" tab at the bottom of the main Sortables interaction web page.

Two things worth mentioning at this point:

  • If one of your lists starts off empty, or if there's any chance that a user might remove all of the items from a list and then try to put items back into the now-empty list, you need to set a minimum height for that <ul>, so that even when empty, the <ul> is large enough to accomodate a single list element. In Firefox and Safari, you can set the minimum height using the min-height CSS style, but if you have to support IE 7, you'll have to add two additional height styles (like so):
    • min-height:50px;
      height:auto !important;
      height:50px;

  • In my early experiments with this, I found that if you drag an item of a list, the list item's width gets shrunk to the width of the longest unbroken string of text in the list item. I'm not sure why it does that, but you can negate that effect by either defining a set width for the <li> elements, or by defining a "helper" with a set width (a helper is a visual representation of the item being moved, using something graphical like an icon).

So, armed with this knowledge about the Sortables interaction, I was able to build the tool required by my clients. Every time a volunteer was moved into or out of a committee, the receive or remove event would make an AJAX call to update the volunteer's record (either providing the id of the committee they were placed in or removing it), and it would run a function that updated the vacancy count for that committee specific to that type of person and counted the overall number of vacancies for that committee (to determine if the committee had been "filled"). I also added a few toggles allowing them to hide extraneous information when they only wanted to see the data pertinent to doing placements for a particular committee. The final challenge was to scale everything so that the tool could be viewed with a projector, so that the members of the group responsible for making the placements could work on it collaboratively.

I wasn't comfortable sharing an exact copy of the tool I created, but I have posted a facsimile that's fairly close to it, minus any real-life data and any AJAX calls to save the placements between page reloads. You can view it here (Note: it doesn't work in IE 7):

https://bcswartz.github.io/jQuery-dragAndDrop-memberPlacement-demo/

...I provided instructions at the top, but quite honestly I think most IT-inclined folks could figure it out without them.

It's just one example of some of the really cool (yet practical) user interfaces made possible with jQuery and jQuery UI.

Wednesday, January 7, 2009

Introducing the tableFormSynch jQuery Plugin

These days, there are a number of options for creating tables where a user can click on a cell and edit the data in that cell using JavaScript (CFML's <cfgfid>, the Jeditable jQuery plugin, etc.). Those work fine for simple tables, but they're not great solutions when you want to:

  • Work with record data you're unwilling or unable to display in the table, lest the table become too long horizontally.
  • Update data related to the row record that could have multiple values (example: the list of skills an employee has).

My new plugin, tableFormSynch, is designed to provide a workable alternative for those situations. It works in conjunction with the jQuery metadata plugin (http://plugins.jquery.com/project/metadata) to bind a table to a form such that you can populate the form with the data stored in a particular row and then use the form to update the data and write it back to the row. It also has functions for creating a new row based on the data in the form, deleting a selected row, and clearing the form of all values. It works with all form elements, including checkboxes, radio buttons, and <select>.

Because the data for each table row is stored in metadata, you don't have to display all of the data in the cells of the row: show only the most important information in the row and show the rest of the information in the form. Values from multiple related records can be stored in the metadata as arrays and viewed/updated via the form using either checkboxes or multi-select <select> boxes.

The only thing you have to watch out for is to make sure that you replace any single-quotes and double-quotes in your data before inserting that data in the metadata string (the plugin documentation covers that in more detail).

The plugin doesn't perform any AJAX operations, so you're free to use your preferred AJAX functions to write and retrieve data from the server. The plugin also isn't particular about how you populate the data in your rows, so you could generate the rows using any server-side technology: CFML using <cfoutput>, <cfloop>, or an IBO, PHP, ASP, etc. You're also free to use your favorite functions for validating the form data. To view a demo and download the plugin, visit:

https://bcswartz.github.io/jQuery-tableFormSynch-plugin-demo

Wednesday, December 3, 2008

Idea: Give Adobe Bolt Collaboration Features

In my last blog post, I suggested that Adobe include a list of CFML community resources in the upcoming Bolt IDE in order to promote the community to isolated developers who might otherwise be unaware of all the resources out there.

After thinking about it a bit more, it occurred to me that maybe Bolt could take it one step further. Instead of simply using Bolt to point developers to the community, have Bolt bring the community to the developer. Build in an RSS viewer that displays the latest ColdFusion posts from Adobe Feeds. Put in a communicator tool so the developer can converse with other CFML programmers via IM or Twitter. Let the developer screen-share their code with other developers both inside and outside of their organization. Integrate geolocation into Bolt and show the developer a list of other Bolt users (and maybe Adobe user groups) that are nearby. Instead of using e-mail and message boards to communicate with CFML developers, Adobe could broadcast any news announcements to all of the Bolt installs, and Bolt users could submit questions to Adobe and other users via discussion forums displayed in a window of the IDE that gets refreshed automatically.

I'll admit, it's a pretty pie-in-the-sky idea. Given that Adobe only has a finite amount of time and resources, I would certainly not want Adobe to leave out any traditional IDE features, the things that allow developers to code quickly and efficiently, in order to take the time to add all of the things I just suggested.

But if they did have a little extra time, I think adding even one or two simple collaboration/informational features would certainly enhance the product, and perhaps set a trend for other IDEs to follow.

Tuesday, December 2, 2008

Reaching the "Invisible" CFML Programmers

On Monday, Sean Corfield's thoughts on how Adobe MAX 2008 went were published on the Fusion Authority website. One of the events Sean cited in his article was a Birds of a Feather session moderated by Adrian Moreno about bridging the gap between expert/guru CFML developers (the ones most visible in the online CFML community) and "9 to 5" CFML developers.

I don't know the details of what was discussed in that session, but it relates to an issue that crosses my mind every once in a while: how do you reach out to developers when you don't know who or where they are? And, conversely, how do we help these "invisible" developers find (and participate in) the community?

I was a full-time ColdFusion developer for almost two years before I really became aware of the ColdFusion community. My predecessor, to my knowledge, never participated in the CFML community or went to any conferences or user groups, so it never crossed my mind that such resources existed. I don't remember how or when I realized that there was a community of folks with which I could converse about ColdFusion development (though it was probably at CFUnited '05), but the point is is that it wasn't an automatic process.

I think this is an area where Adobe needs to step up and promote the community as part of the overall "ColdFusion package". Every sale of ColdFusion should include a list of CFML community resources and a statement that encourage organizations to share that list with any ColdFusion developers they are aware of. If Adobe is skittish about including links to resources that might disappear over time, at the very least they can include Adobe-sponsored resources like Adobe Feeds or the new Adobe Groups site.

Even that kind of effort might not reach all the CFML developers out there: in some organizations (like mine) where the ColdFusion server is running in a shared environment, the organization that owns the CF license may not know who all is using the CF instance. So here's another idea: put links to community resources into the new Adobe Bolt. If Bolt is meant to be the premier IDE for CFML developers, then there's a good chance that even the "invisible" CFML developers will grab it and gain access to all the resources it provides.

Monday, October 27, 2008

Applications Are Only as Beautiful as the Processes They Replicate

In an ideal application development process, you work with the client to get an accurate picture of all of the business logic involved in the process the application is supposed to handle, and the end result is a robust system built with clean, understandable code.

But it doesn't always work out that way (some would say it never works out that way). Most of us have had to deal with "scope creep." In fact, one could argue that most modern CFML-coding frameworks and patterns came out of the need to deal with "scope creep" and other reasons for changing our applications.

But sometimes the challenge in creating a clean application comes from the nature of the business "logic" itself, the real-world process that your application is supposed to mimic and replace. It occurred to me the other day that that is often the biggest hurdle I have to overcome with the applications that I'm asked to construct.

When I work with my clients to figure out what exactly what tasks the software needs to perform, I often discover that the processes at work are often riddled with exceptions and conditionals. Sometimes my clients are consciously aware of these exceptions, but other times I have to point them out and we have to figure out how they need to be dealt with.

We humans can handle exceptions within our thought processes very easily. Computer logic, on the other hand, doesn't handle exceptions so casually (which is probably why errors can be referred to as "exceptions"). Coding for even a single exception to an otherwise iron-clad rule can make the code involved twice as complex and perhaps a bit less than pristine.

While we do all we can as responsible programmers to deliver a beautifully-coded application, I think that sometimes there's no avoiding the touch of ugliness that comes from trying to represent and replicate an "ugly" human-driven process.

Wednesday, September 3, 2008

CF411 and ColdFusion for Educational Use (Oh, And That New Browser...)

Blogging bullet-point style tonight:

  • Charlie Arehart's new CF411 site has a MASSIVE amount of links to tools and resources for CFML and web development. Stop what you're doing right now, go to the page, and store it somewhere (your bookmarks, Delicious, wherever).

  • The announcement that ColdFusion 8 Enterprise is now available for free for educational use (in other words, for learning purposes) was made on Monday. You can find out more at https://freeriatools.adobe.com/coldfusion/

    While I'm glad the announcement is out, I just wish it had been promoted better. There's still nothing about it up on the Adobe home page or even on Adobe's ColdFusion product page. Why not?

  • Last (and least...), Google surprised everyone this week with their new Chrome web browser. It got so much attention that everyone stopped talking about the iPhone, which is admittedly pretty impressive.

    Like everyone else, I've played with it. Here's my take on it (yep, more bullet-points):

    • It runs pretty well.
    • It does seem to run JavaScript more quickly than other browsers.
    • It has a few nice innovative features.
    • It can be quirky at times and it has some flaws (but it is a beta).
    • It has promise, but it doesn't provide any new functionality that I find particularly useful to me.
    • FireFox will remain my browser at work and at home.