Created
October 19, 2016 11:52
-
-
Save thinker3197/bcdb1d1ec601886a9f35b2073ed0a600 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
const drag = (() => { | |
return { | |
move: function(elem, xpos, ypos) { | |
elem.style.left = xpos + 'px'; | |
elem.style.top = ypos + 'px'; | |
}, | |
start: function(elem, container, event) { | |
let posX = event.clientX, | |
posY = event.clientY, | |
elemTop = (elem.style.top).replace('px', ''), | |
elemLeft = (elem.style.left).replace('px', ''), | |
elemWidth = parseInt(elem.style.width), | |
elemHeight = parseInt(elem.style.height), | |
containerWidth = parseInt(container.style.width), | |
containerHeight = parseInt(container.style.height); | |
container.style.cursor = 'move'; | |
let diffX = posX - elemLeft, | |
diffY = posY - elemTop; | |
document.onmousemove = function(event) { | |
let posX = event.clientX, | |
posY = event.clientY, | |
aX = posX - diffX, | |
aY = posY - diffY; | |
if(aX < 0) | |
aX = 0; | |
if(aY < 0) | |
aY = 0; | |
if(aX + elemWidth > containerWidth) | |
aX = containerWidth - elemWidth; | |
if(aY + elemTop > containerHeight) | |
aY = containerHeight - elemHeight; | |
drag.move(elem, aX, aY); | |
} | |
}, | |
stop: function(container) { | |
container.style.cursor = 'default'; | |
document.onmousemove = function() {}; | |
} | |
} | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment