2015年1月2日星期五

HTML Drag and Drop

Here is a basic drag and drop function which works fine on Chrome and Firefox. But without set some data in the dataTransfer object, it doesn't really behaves right.In Firefox it doesn't trigger any of these dragOver, dragEnter or drop events.

drag me
drop here

drag me
drop here

Here is the complete code.

<div draggable="true" style="width:64px;height:64px;border:1px solid #666;background:#acf;margin:0.25em;padding:0.25em;cursor:pointer;float:left;" id="move">drag me</div>
<div style="padding:0.25em;width:15ex;height:15ex;border:1px solid #666;background:#eee;margin:0 0 0 15ex;float:left;" draggable="true" id="target"> drop here</div>
<script>
$(document).ready(function() {
    $('#move')
    
        // Set the element as draggable.
        .attr('draggable', 'true')

        // Handle the start of dragging to initialize.
        .bind('dragstart', function(ev) {
            ev.originalEvent.dataTransfer.setData("target", '#' + ev.target.id);
            return true;
        })

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

    $('#target')

        // 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;
            $(ev.target).append($(dt.getData("target")));
            return false;
        });
});
</script>