Drag and Drop with script.aculo.us and Rails - Drag and Drop
(Page 2 of 4 )
The ability to directly manipulate on-screen objects is often taken for granted in desktop applications, but web interfaces have been slow to follow—largely due to the complex DOM manipulation it requires. script.aculo.us changes that equation, and provides surprisingly easy and powerful support for drag-and-drop interfaces. That means that web developers can decide to use drag and drop based primarily on usability concerns, rather than technical ones. As with visual effects, it’s important to remember that drag and drop is often not the best solution to an interface problem. But when it is, script.aculo.us makes it painless.
Draggables
script.aculo.us provides a Draggable class that’s used to add draggability to DOM elements. To get started, create a new template file, draggables.rhtml. In it, add this:
<div id="dragDIV" class="green box">drag</div>
<%= javascript_tag "new Draggable('dragDIV')" %>
When the page is loaded (http://localhost:3000/chapter4/draggables), the JavaScript statement causes a new instance of theDraggableclass to be created, tied to the given element ID. From then on, you can drag the element around the page. Notice how it becomes slightly transparent while it is dragged—it uses the sameOpacityeffect we explored earlier. TheDraggable constructor takes an optional second parameter for options, which will be detailed later.
Rails provides thedraggable_elementhelper to create draggables. Just likeDraggable.initialize, the first argument is the ID of an element, and the second is a hash of options. For example:
<div id="helperDIV" class="green box">helper</div>
<%= draggable_element :helperDIV %>
The output ofdraggable_elementis a<script>element with anewDraggablestatement. If you just need the JavaScript statement without the<script>tags, usedraggable_element_jsinstead. For example:
<div id="clickDIV" class="green box">
<%= button_to_function "Make draggable",
draggable_element_js(:clickDIV)
%>
</div>
For usability, it’s often a good idea to change the cursor when it’s over a draggable element. The CSS cursor property makes it easy. For example:
<div class="green box" style="cursor:move">drag</div>
When the user mouses over this element, the cursor will change to a “move” icon (as in Figure 4-1), indicating that the element is draggable. Of course, the CSS doesn’t need to be inline—it could easily be part of the external stylesheet.

Figure 4-1. Using the CSS cursor property
Next: Draggable options >>
More Ruby-on-Rails Articles
More By O'Reilly Media
|
This article is excerpted from chapter four of Ajax on Rails, written by Scott Raymond (O'Reilly, 2007; ISBN: 0596527446). Check it out today at your favorite bookstore. Buy this book now.
|
|