Skip to content

Instantly share code, notes, and snippets.

@remainstheday
Created December 31, 2016 19:40
Show Gist options
  • Save remainstheday/23e49994c583dccd6faff365f538f197 to your computer and use it in GitHub Desktop.
Save remainstheday/23e49994c583dccd6faff365f538f197 to your computer and use it in GitHub Desktop.
vanilla javascript drag objects
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.offsetLeft;
y_elem = y_pos - selected.offsetTop;
}
// 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;
if (selected !== null) {
selected.style.left = (x_pos - x_elem) + 'px';
selected.style.top = (y_pos - y_elem) + 'px';
}
}
// Destroy the object when we are done
function _destroy() {
selected = null;
}
// Bind the functions...
document.getElementById('draggable-element').onmousedown = function () {
_drag_init(this);
return false;
};
document.getElementById('draggable-element2').onmousedown = function () {
_drag_init(this);
return false;
};
document.onmousemove = _move_elem;
document.onmouseup = _destroy;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment