Pure JavaScript Draggable
http://www.dte.web.id
by Lindow
HTML
<div class="elements">
<div class="element">Drag me!</div>
<div class="element">Drag me!</div>
<div class="element">Drag me!</div>
<div class="element">Drag me!</div><div class="element">Drag me!</div>
<div class="element">Drag me!</div><div class="element">Drag me!</div>
<div class="element">Drag me!</div>
</div>
CSS
.element {
width: 100px;
height: 100px;
background-color: #666;
color: white;
padding: 10px 12px;
cursor: pointer;
position:absolute;
/* important (all position that's not `static`) */
}
#element span:hover {cursor:text;}
JavaScript
var selected = null, // Object of the element to be moved
x_pos = 0,
y_pos = 0, // Stores x & y coordinates of the mouse pointer
x_elem = 0,
y_elem = 0; // Stores top, left values (edge) of the element
// Will be called when user starts dragging an element
function _drag_init(elem) {
// Store the object of the element which needs to be moved
selected = elem;
x_elem = x_pos - selected.getBoundingClientRect().left;
y_elem = y_pos - selected.getBoundingClientRect().top;;
selected.style.background = 'red';
}
// Will be called when user dragging an element
function _move_elem(e) {
x_pos = document.all ? window.event.clientX : e.pageX;
y_pos = document.all ? window.event.clientY : e.pageY;
x = (x_pos - x_elem)
y = (y_pos - y_elem)
if (selected !== null) {
selected.style.webkitTransform = 'translate3d(' + String(x) + 'px,' + String(y) + 'px, 0px)';
selected.style.msTransform = 'translate3d(' + String(x) + 'px,' + String(y) + 'px, 0px)';
selected.style.transform = 'translate3d(' + String(x) + 'px,' + String(y) + 'px, 0px)';
}
}
// Drop the object when we are done
function _destroy() {
selected = null;
}
// BY CLASS
// _drag_init(this);
// return false;
var elements = document.getElementsByClassName('element');
for(var i = 0; i < elements.length; i++) {
var element = elements[i];
element.onmousedown = function() {
_drag_init(this);
return false;
}
}
document.onmousemove = _move_elem;
document.onmouseup = _destroy;