Draggable Without JQuery UI

by 20yco

HTML

<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>

<div class="container">

</div>

CSS

div {
    cursor: move;
    width:70px;
    height:70px;
    background:black;
    z-index: 1;
    margin:2px;
    float:left;
    
}
.active {

}

.container {
	width:600px;
	height:400px;
	background:#ccc;
	margin-top:150px;
}

JavaScript

$('div').on('mousedown', function (e) {
    
    var $this = $(this);

    $this.addClass('active');
    
    var oTop = e.pageY - $('.active').offset().top;
    var oLeft = e.pageX - $('.active').offset().left;
    
    $(this).parents().on('mousemove', function (e) {

        $('.active').offset({

            top: e.pageY - oTop,
            left: e.pageX - oLeft

        });
             
    });
    
    $('body').on('mouseup', function () {

        $this.removeClass('active');
        $('body').unbind('mouseup');

    });
    
    return false;    
});