jQuery, drag & drop, and relative sizing through CSS

Posted by Elf Sternberg as css, Design, jquery

One of the things I like to use with CSS is percentages. Often, this goes a bit over the top; right now, I have a two column layout that looks something like this:

.leftcolumn {
    float: left;
    width: 22.340425%;
    margin-right: 1.06382%;
    overflow: hidden;

.rightcolumn {
    float: left;
    width: 76.59574%;
    margin-right: 0;

Which is about as “relative” as you can imagine. Combined with max-width and some judicious (and very sparse) HTML nesting, however, you can do some pretty nice resizing things before you have to go to the media-query and up–  or downsize your entire layout.

Unfortunately, if you want to use jQuery UI’s drag-and-drop feature, percentages suck. jQuery will take them literally, and apply them to the helper in accordance with the first common relatively positioned parent, which can be disastrous; I was ending up with draggables so wide they didn’t fit inside the drop zone.

Fortunately, there is a fix. Draggables have a list of options, one of which is “helper.” The most commonplace arguments to helper are “clone” and “original.” The first makes a copy of the dragged object; the second takes the dragged object out of its original flow and makes it mobile. Taking an object out of its flow, or making a copy and attaching it to a parent object, can have the aforementioned disastrous side effects. Helper can, however, take as an argument a function that returns a suitable object for dragging. By creating a copy of the original object, and assigning to it a hard width derived from the calculated width of the original, you can ensure that the helper’s rectangle matches your eye’s expectations. Like so:

    'helper': function() { return $(this).clone().css('width', this.offsetWidth)[0]; }
    ... /* other options */

In this case, this refers to the object to be copied, obviously. jQuery passes it as context. This works for jQuery 1.5 and up, and jQuery UI 1.8.2 and up.

Comment Form

Subscribe to Feed



August 2011
« Jul   Sep »