Dragging

Dragging with jQuery UI and Native JavaScript.

by gizmovation

HTML

<div id="jquery" style="top:100px;left:0px;">jQuery<br>I am not going out.</div>
<div id="window" style="top:100px;left:100px;">Native (Using window)<br>I can go outside!</div>
<span>0,0</span>

CSS

*{
    -webkit-user-select:none;
}
div{
    width: 100px;
    height: 100px;
    background:white;
    border:1px solid #aaa;
    cursor: url(https://mail.google.com/mail/images/2/openhand.cur), default !important;
    display:inline-block;
    position:absolute;
}
div:active{
    cursor: url(https://mail.google.com/mail/images/2/closedhand.cur), default !important;
}

JavaScript

//jQuery, fast, but not I wanted. Won't be able to be draggable
//outside the window.
$("div#jquery").draggable({ containment: [-5000, -5000, 5000, 5000] });


//Native, do what I expected, but eventually I don't want to type this bunch of code.
var dragging = false,
    x, y, Ox, Oy,
    ele=document.querySelector("div#window");
ele.onmousedown = function(ev) {
    dragging = true;
    x=ev.clientX;
    y=ev.clientY;
    Ox=this.offsetLeft;
    Oy=this.offsetTop;
}
window.onmousemove = (function(ev) {
    $("span").html(ev.clientX + "," + ev.clientY);  //showing
                                                    //coordinates
    if (dragging == true) {
        var Sx=ev.clientX-x+Ox,
            Sy=ev.clientY-y+Oy;
        ele.style.top=Sy+"px";
        ele.style.left=Sx+"px";
        return false;
    }
});
window.onmouseup=function(ev){
    dragging&&(dragging=false);
}