Skip to content

Instantly share code, notes, and snippets.

@aclave1
Created February 2, 2014 07:45
Show Gist options
  • Save aclave1/8764387 to your computer and use it in GitHub Desktop.
Save aclave1/8764387 to your computer and use it in GitHub Desktop.
Simple Javascript draggable element
/**
Pass in a dom ID string or a dom node and to make it draggable.
*/
var Draggable = function(elem) {
var that = this;
var el = (typeof elem === 'string') ? document.getElementById(elem) : elem;
var offX, offY;
this.mouseDown = function(e) {
offX = e.clientX - parseInt(el.offsetLeft);
offY = e.clientY - parseInt(el.offsetTop);
window.addEventListener('mousemove', that.mouseMove);
window.addEventListener('mouseup', function() {
window.removeEventListener('mousemove', that.mouseMove);
});
};
this.mouseMove = function(m) {
el.style.position = 'absolute';
el.style.top = (m.clientY - offY);
el.style.left = (m.clientX - offX);
};
el.addEventListener('mousedown', that.mouseDown);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment