Friday, January 10, 2014

Moving Draggables Within The DOM Tree

The jQuery UI draggable widget let's the user move elements around on the screen. This concept is all the more powerful when used in conjunction with a droppable container. This is essentially a target for the user to drop their draggables. One drawback is that despite the appearance of having been dropped into the new DOM node, this is not the case. The only thing that changes when draggables are moved around on the screen are their positional CSS properties. A lot of the time, it would be nice to have the draggable move not only in presentation properties, but to change it's position in the DOM tree too.

This example illustrates how that is done. For example, here you can see both draggable elements as they appear when moved into the droppable container. They inherit style properties from the container, which is nice. In this case, it's the layout and the font that's affected.

We could add even more specificity with descendent selectors that apply to the dropped draggables. These would apply by virtue of the draggable becoming a child of the droppable, which isn't the case by default.

To make this work, all we need to do is reset the positional CSS properties applied to the draggable element by the widget. By resetting, I mean setting the default values. So position becomes static, top becomes auto, and left becomes auto. Having done that, we just need to use the appendTo() function to relocate the draggable to it's new parent. Then the CSS applied there will do it's thing to properly position the elements.

This is one line of JavaScript, and it's triggered inside the drop callback function we've passed to the droppable widget. The ui.draggable object is the element we're working with.

No comments :

Post a Comment