jQuery UI – Mouse Interactions: Dragging and Dropping

Dragging and dropping an element usually go together. There might be moments where just dragging around an element is enough, but usually you’ll want both features. A draggable DOM element can be moved around by clicking and then moving the mouse. Droppable elements can accept draggable elements.

Dragging and dropping aren’t features that are available to web pages by default, although they are very common idioms of everyday computer use. Thankfully, jQuery UI makes it simple and approachable. Although the actions are coupled, they require separate calls.

A component is made draggable by calling the jQuery UI draggable method, $(selector) .draggable(), as simple as that. Like many of the method calls you’ve seen in this book, the .draggable() method is overloaded, reducing namespace clutter. (See Table 9-1.)

Table 9-2 shows the different options for draggable elements.

In a very similar fashion, the $.droppable() method is also overloaded. Table 9-3 lists all available $.draggable() methods.

All draggable components have a class of ui-draggable. While in a dragging state, the class changes to ui-draggable-dragging.

The following example uses both drag and drop to demonstrate a visual way of dividing tasks. At the top are square elements that each represent a task. At the bottom are the different states of a task: in progress or finished. By making the tasks draggable, the end user can intuitively organize tasks. Upon dropping a task box, the task box changes color. Figure 9-1 shows the output of this code.

<!DOCTYPE html>

<html>

<head>

<link type=”text/css”

href=”css/ui-lightness/jquery-ui-1.8.13.custom.css” rel=”stylesheet” />

<script src=”http://code.jquery.com/jquery-1.7.1.js”></script>

<script src=”js/jquery-ui-1.8.13.custom.min.js”></script>

<style type=”text/css”>

div {

width : 150px;

margin-bottom : 20px;

margin-right : 20px;

float: left;

}

#flow {

float: left;

height : 400px;

}

#task3 {

clear: both;

}

</style>

<script type=”text/javascript”>

$(function(){

$(‘div[id^=”task”]’).draggable({

snap : ‘div’,

snapMode : ‘both’

// snap tolerance

});

$(’#flow’).droppable({

drop : function( event, ui ) {

$( this ).addClass( “ui-state-highlight” );

}

});

});

</script>

</head>

<body>

<div id=”task1″ class=”ui-widget-content”>

<p>Task 1</p>

</div>

<div id=”task2″ class=”ui-widget-content”>

<p>Task 2</p>

</div>

<div id=”task3″ class=”ui-widget-content”>

<p>Task 3</p>

</div>

<div id=”flow” class=”ui-widget-content”>

<p class=”ui-widget-header”>In Progress</p>

</div>

<div id=”flow” class=”ui-widget-content”>

<p class=”ui-widget-header”>Finished</p>

</div>

</body>

</html>

Code snippet is from drag-drop.txt

Source: Otero Cesar, Rob Larsen (2012), Professional jQuery, John Wiley & Sons, Inc

Leave a Reply

Your email address will not be published. Required fields are marked *