Skip to content

A podcast for those who design, develop and run websites.

Boagworld is the web design blog of Paul (the Wurzel) Boag who lives in the heart of rural Dorset. He produces a weekly podcast with Marcus (pop star) Lillington on all things relating to building and running websites. They also run web design agency - Headscape.

Latest Shows

199. Time to generalise
This week on Boagworld: The changing role of web designers, Colin Firth on content and Becky Jones talks about the changes at Google.
198. jQuery goodness
This week on Boagworld: Dave interviews Remy Sharp creator of jQuery for Designers and Matt Bee dares to review the Website Owners Manual.
197. Energise your ecommerce
This week on Boagworld: We examine ways to improve the conversion rate on your ecommerce site, review CSS Mastery 2nd Edition and take a look at Zen Coding.
196. Interview with Kevin Rose
This week on Boagworld: We interview the founder of Digg.com Kevin Rose, take a first look at Codeslam and plan the future of the show.
195. Christmas Cheer
On our 2009 christmas special: Your favourite tweets of the year, a review of 24 ways, gifts for geeks and web design trends for 2010.

or view all shows

Have your say

Become a part of the Boagworld community...

Creating a Draggable Sitemap with JQuery

Posted in Tech/Development on: Tuesday, September 1, 2009 by Dave McDermid

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/

What did you think about this post?

43 Tweets 1 Other Comment

One Comments

Comments are for the discussion of this post. If you have other questions / comments then post them to the forum or send me an email

  • Nick says:

    Now, how about merging this with the slickmap css. Go into edit mode, drag and drop, add new pages. Then save and see it with the Slickmap CSS.

    This comment was originally posted on WebAppers

Additional comments powered by BackType

Additional Information

Produced by Headscape

Boagworld is produced by the web design agency Headscape founded by Marcus, Paul and Chris Scott. Headscape also has a number of other talented guys who blog. Check them out.

  • Craig Rowe is one of our amazing developers and writes some superb posts on everything from .net to AIR apps.

  • Ed Merritt is a Headscape designer who's blog contains examples of his work and a number of free Wordpress themes.

  • Dave McDermid is a Headscape developer who has an excellent blog. He blogs on everything from AJAX to security.

  • Rob Borley is one of our project managers and blogs regularly on client and project management issues.

  • Leigh Howells is our multimedia design guru (whatever one of those is). He blogs on a mixture of design and music.

Paul elsewhere

Paul just can't shut up. He publishes regular audioboos, has a personal blog and is addicted to twitter. He also writes and speaks regularly. Check out the most recent below:

close
Are you ready for the 200th Boagworld? Join us for 12 hours of streaming video on Friday 12th February from 10AM (UK time).