Pure JavaScript Draggable

http://www.dte.web.id

by S_YOU

HTML

<div class="draggable">Drag me!</div>

CSS

.draggable {
  width:100px;
  height:100px;
  background-color:#666;
  color:white;
  padding:10px 12px;
  cursor:move;
  position:relative; /* important (all position that's not `static`) */
}

JavaScript

// Will be called when user dragging an element
function _move_elem(e) {
    this.mousex = document.all ? window.event.clientX : e.pageX;
    this.mousey = document.all ? window.event.clientY : e.pageY;
	if (this.dragging) {
		this.style.left = (this.mousex - this.pos_x) + 'px';
		this.style.top = (this.mousey - this.pos_y) + 'px';
	}
}

// Destroy the object when we are done
function _destroy() {
    this.dragging = false;
}

// Bind the functions...
var elem = document.getElementsByClassName('draggable')[0];
elem.mousex = elem.mousey = elem.pos_x = elem.pos_y = 0;
elem.onmousedown = function () {
	this.pos_x = this.mousex - this.offsetLeft;
	this.pos_y = this.mousey - this.offsetTop;
	this.dragging = true;
    return false;
};

elem.onmousemove = _move_elem;
elem.onmouseup = _destroy;
elem.onmouseleave = _destroy;