jQuery Drag

Drag a box powered by jQuery scripts

by surfine

HTML

<div id="drag">Drag me</div>

CSS

#drag {
    position: absolute;
    top: 10px; left: 10px;
    height: 100px;
    width: 100px;
    background: #EDEDED;
    border: 1px solid #C3C3C3;
    border-radius: 4px;
    color: #8B8B8B;
    font-family: "Lucida Sans Unicode", "Lucida Grande", sans-serif;
    font-size: 12px;
    line-height: 100px;
    text-align: center;
    
    /* turn text highlight off */
    -webkit-touch-callout: none;
    -webkit-user-select: none;
    -khtml-user-select: none;
    -moz-user-select: none;
    -ms-user-select: none;
    user-select: none;
}

JavaScript

var axisY = 0;
var axisX = 0;
var clicking = false;

$('#drag').mouseup(function(){
    clicking = false;
});

$('#drag').mousedown(function(){
    clicking = true;
});

$(document).mousemove(function(e) {
    axisY = e.pageY; /* obtain the vertical position of your pointer */
    axisX = e.pageX; /* obtain the horizontal position of your pointer */
    axisY = axisY - 50; /* half the height of your element to center it while dragging (in my case, it's 50) */
    axisX = axisX - 50; /* half the width of your element to center it while dragging (in my case, it's 50) */
 
    if (clicking === true) {
        $('#drag').css({'position': 'absolute', 'top': axisY, 'left': axisX }); /* drag the element */
    } else {
        // do what ever you like or do nothing
    }
});