Dragging Data Around

This is an example of how to bind application data to draggables, and decouple data access in the drop event callback functions.

by Adam Boduch

HTML

<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css">
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
<div class="products">
    <div class="product ui-widget ui-widget-content" data-price="5">
        <div>Mug</div>
        <div>$5</div>
    </div>
    <div class="product ui-widget ui-widget-content" data-price="10">
        <div>Book</div>
        <div>$10</div>
    </div>
</div>

<div class="cart ui-widget ui-state-default">
    <span>Cart ($<span class="price">0</span>)</span>
</div>

CSS

.products {
    float: left;
}
.product {
    width: 4em;
    padding: 0.2em;
    text-align: center;
    margin: 0.8em;
    cursor: move;
}

.product div:last-child {
    font-size: 0.9em;
}

.cart {
    float: left;
    width: 30%;
    height: 10em;
    margin-left: 10em;
    background-image: none;
    padding: 0.2em;
}

.cart-active {
    opacity: 0.6;
}

JavaScript

(function( $ ) {
    $.widget( "ui.droppable", $.ui.droppable, {
        ui: function( c ) {
            var ui = this._super( c );
            return $.extend( ui, {
                product: {
                    price: ui.draggable.data( "price" )
                }
            });
        }
    });
})( jQuery );

$(function() {
    $( ".product" ).draggable({
        helper: "clone"
    });

    $( ".cart" ).droppable({
        accept: ".product",
        activeClass: "cart-active",
        drop: function( e, ui ) {
            var $price = $( this ).find( ".price" );
            $price.text( ui.product.price + parseInt( $price.text() ) );
        }
    });
    
});