Creating a Draggable Sitemap with JQuery

A couple of weeks ago I was tasked with building a drag-and-drop sortable sitemap for our in-house content management system. After a number of failed attempts, here’s how we ended up solving the problem.

There are a handful of javascript libraries and plugins available that attempt this task, but none of them worked flawlessly with our HTML. The real issue here is that javascript alone cannot produce a slick solution, the HTML and CSS need to be carefully constructed to ensure that the experience is seamless and pleasant.

The HTML.

Our HTML consists of nested unordered lists, with each list item containing a definition list for the title, page type, publish status, and action links for editing or deleting the page. The feature for expanding and collapsing child pages already existed, making things extra fun.

[html]
<ul id=”sitemap”>
<li>
<dl>
<dt><a href=”#”>expand/collapse</a> <a href=”#”>Page Title</a></dt>
<dd>Text Page</dd>
<dd>Published</dd>
<dd><a href=”#”>delete</a></dd>
</dl>
<ul><!–child pages–></ul>
</li>
</ul>
[/html]

The requirements.

The behaviour had to intuitive for the user, they need to be able to reorder pages and move entire sections to new parents. It had to be clear to the user where a page would end up when they dropped it (ie. between pages or as a child page).

Simplifying the task.

When one page is dropped over another page, there are three possible outcomes. The page can end up before, after or as a child. This gets particularly tricky at the boundary point between the last child of a sub list and the following sibling. If the resulting location of where a page ends up is the difference of a couple of pixels, the user could become frustrated. We decided to simplfy the problem so that a page could be dropped only before items or as children of items. The only limitation here is that you couldn’t easily drop an item as the last child of a list, but this is only a minor issue as moving the last child up would achieve the same result. You can also drop an item on the parent to cause it to become the last child, but this isn’t so obvious really.

This means for each item on our list we now need to identify two areas where the user can drop the page, on the page to be a child, and above the page to be a sibling.

The javascript.

The great thing about jQuery / jQuery UI is how it lets me write the code I want to write, and takes care of cross-browser behaviours and gaps in DOM manipulation. Anyone who has attempted at creating drag and drop functionality for a website will be well aware of the headaches involved in getting everything to work smoothly across browsers. jQuery UI seems to handle this brilliantly.

The first thing I want to do is create a div inside the list item to act as a dropzone for placing items as siblings.

    $('#sitemap li').prepend('<div class="dropzone"></div>');

piece of cake.

To allow an item to be dragged, we simply call the draggable() function on the items that can be dragged.

$('#sitemap li').draggable({
    handle: ' > dl',
    opacity: .8,
    addClasses: false,
    helper: 'clone',
    zIndex: 100
});

As we are dealing with nested lists, it is important that only the definition list inside our list item acts as a handle, otherwise our old friend Internet Explorer can get a little confused over who’s meant to be moving and who should be staying where they are. By specifying ‘clone’ we create a duplicate list item that follows the mouse, while the original item waits patiently for us to decide where it should belong. An opacity of 0.8 and a high zIndex keeps the clone on top of everyone else and slightly opaque. It’s the little touches that really count.

The magic.

$('#sitemap dl, #sitemap .dropzone').droppable({
    accept: '#sitemap li',
    tolerance: 'pointer',
    drop: function(e, ui) {
        var li = $(this).parent();
        var child = !$(this).hasClass('dropzone');
        //If this is our first child, we'll need a ul to drop into.
        if (child && li.children('ul').length == 0) {
            li.append('<ul/>');
        }
        //ui.draggable is our reference to the item that's been dragged.
        if (child) {
            li.children('ul').append(ui.draggable);
        }
        else {
            li.before(ui.draggable);
        }
        //reset our background colours.
        li.find('dl,.dropzone').css({ backgroundColor: '', borderColor: '' });
    },
    over: function() {
        $(this).filter('dl').css({ backgroundColor: '#ccc' });
        $(this).filter('.dropzone').css({ borderColor: '#aaa' });
    },
    out: function() {
        $(this).filter('dl').css({ backgroundColor: '' });
        $(this).filter('.dropzone').css({ borderColor: '' });
    }
});

Ok. That’s a fair chunk of code, let’s break it down.
We only want to accept sitemap list items, we don’t care about other items they care to drop here.
The tolerance specifys the drop item to be the element under mouse pointer, we’re expecting the user to place their mouse where the item should end up.
When the drop happens, this is how we decide what to do:
We set the variable ‘li’ to be the parent of the dropzone (as both the definition list and the dropzone div are children of the list item). This is just for convenience.
When the user drops the page, we need to decide what they landed on, if it has a class ‘dropzone’ then we are placing the dropped item before us. Otherwise we are placing this as a child.
As the item is being dragged around, it is imperitive to give an indication as to where it will end up. We can do this by conditionally applying a background colour to whichever item we are hovering over. For the ‘dropzone’, we instead apply a border colour, as we want it to display as a solid line between the two items.

At this point we can also fire off our update in an ajax post to the server, in order to commit the change.

The CSS.

The secret to the interface working really well is CSS. By making sure we have the right paddings and heights in the right places we give the user enough space to comfortably drop items. If we keep the space around the definition list tight, and apply a 4px border plus 6px height to the ‘dropzone’ div, we give the user 10 pixels of droppable area. This is plenty to guarantee the user will be comfortable. The 4px border gives us a strong, clear indication that the item will be dropped as a sibling.

Extra spice

In the demo you’ll notice the addition of an undo stack. This is a great fall back for when a user moves a page to the wrong place but forgets where it came from. This will be covered in a separate tutorial.

Demo: http://boagworld.com/demos/sitemap

For more info, checkout the jQuery UI docs: http://jqueryui.com/demos/

Headscape

Boagworld