drag & drop

by gnepud

HTML

<div id="newschool">
    <div class="dragme">Drag me!</div>
    <div class="drophere">Drop here!</div>
</div>

CSS

.dragme {
    width: 64px;
    height: 64px;
    border: 1px solid #666;
    background: #acf;
    margin: 0.25em;
    padding: 0.25em;
    cursor: pointer;
}
.drophere {
    padding: 0.25em;
    width: 15ex;
    height: 15ex;
    border: 1px solid #666;
    background: #eee;
    margin: 0 0 0 15ex;
}
.dragover {
    background: #8f8;
}
#newschool {
    clear: both;
}
#newschool .dragme {
    float: left;
}
#newschool .drophere {
    margin: 0 0 0 15ex;
}
#newschool .dragover {
    background: #8f8;
}

JavaScript

/**
 * Quick example of HTML5 Drag & Drop
 *
 * <div id="newschool">
 *     <h2>New school drag and drop</h2>
 *     <div class="dragme">Drag me!</div>
 *     <div class="drophere">Drop here!</div>
 * </div>
 */
$(document).ready(function() {

    $('#newschool .dragme')
    
        // Set the element as draggable.
        .attr('draggable', 'true')

        // Handle the start of dragging to initialize.
        .bind('dragstart', function(ev) {
            var dt = ev.originalEvent.dataTransfer;
            ev.originalEvent.dataTransfer.effectAllowed = 'copy';
            dt.setData("Text", "Dropped in zone!");
            return true;
        })

        // Handle the end of dragging.
        .bind('dragend', function(ev) {
            return false;
        });

    $('#newschool .drophere')

        // Highlight on drag entering drop zone.
        .bind('dragenter', function(ev) {
            $(ev.target).addClass('dragover');
            return false;
        })

        // Un-highlight on drag leaving drop zone.
        .bind('dragleave', function(ev) {
            $(ev.target).removeClass('dragover');
            return false;
        })

        // Decide whether the thing dragged in is welcome.
        .bind('dragover', function(ev) {
            return false;
        })

        // Handle the final drop...
        .bind('drop', function(ev) {
            var dt = ev.originalEvent.dataTransfer;
            console.log(dt.getData("Text"));
            return false;
        });

});