Created
February 2, 2014 07:45
-
-
Save aclave1/8764387 to your computer and use it in GitHub Desktop.
Simple Javascript draggable element
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
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