Drag&Drop (mouse events)

by Alexander Shutov

HTML

<div id="box1" class="box">
    <div class="item"></div>
</div>
<div id="box2" class="box"></div>

CSS

html, body {
    width:100%;
    height:100%;
    padding:0;
    margin:0;
    overflow:hidden;
}
.box {
    width:4em;
    height:4em;
}
#box1 {
    background-color:#a42;
}
#box2 {
    background-color:#24a;
}
#box1.target, #box2.target {
    background-color:#2a4;
}
.item {
    width:2em;
    height:2em;
    background-color:#222;
}

JavaScript

$('body')
    .on('mousemove', function (e) {
    if (holdItem) {
        onMoveItem(e.clientX, e.clientY);
    }
}).on('mouseup', function (e) {
    if (holdItem) {
        onCancelDrag();
    }
}).on('selectstart', function (e) {
    return false;
});
$('.item').on('mousedown', function (e) {
    onStartDrag($(e.target));
    onMoveItem(e.clientX, e.clientY);
}).on('mouseup', function (e) {
    console.log('item mouse up');
}).on('selectstart', function (e) {
    return false;
});
$('.box')
    .on('mouseenter', function (e) {
    if (holdItem) {
        $(e.target).addClass('target');
    }
}).on('mouseleave', function (e) {
    if (holdItem) {
        $(e.target).removeClass('target');
    }
}).on('mouseup', function (e) {
    console.log('mouseup on box');
    if (holdItem) {
        onPlaceItem($(e.target));
    }
    console.log(e.target);
}).on('selectstart', function (e) {
    return false;
});

var holdItem;
var holdParent;

function onStartDrag(item) {
    holdItem = item;
    holdParent = holdItem.parent();
    holdItem.appendTo('body');

    holdItem.css({
        "position": "absolute",
            "pointer-events": "none"
    });
}

function onMoveItem(x, y) {
    holdItem.css({
        "left": x - holdItem.width() / 2 + "px",
            "top": y - holdItem.height() / 2 + "px"
    });
}

function onCancelDrag() {
    holdItem.appendTo(holdParent);
    holdItem.css({
        "position": "static",
            "pointer-events": "auto"
    });
    holdItem = null;
}

function onPlaceItem(target) {
    holdItem.appendTo(target);
    holdParent = target;
}