Skip to content

Instantly share code, notes, and snippets.

@varblob
Last active November 16, 2015 20:42
Show Gist options
  • Save varblob/35f132de5954fe4c2fff to your computer and use it in GitHub Desktop.
Save varblob/35f132de5954fe4c2fff to your computer and use it in GitHub Desktop.
translateTarget(target, dx, dy){
// dragged position in the data-x/data-y attributes
function attr(name, defaultVal) {
return (parseFloat(target.getAttribute('data-' + name)) || defaultVal);
}
function setAttrs(target, attrs){
Object.keys(attrs).forEach((k)=> {
target.setAttribute('data-' + k, attrs[k]);
});
}
var $target = $(target),
oldX = attr('x', 0),
oldY = attr('y', 0),
width = $target.width(),
height = $target.height(),
oldWidth = attr('width', width),
oldHeight = attr('height', height),
oldPx = attr('px', 0),
oldPy = attr('py', 0),
newX = dx + oldPx * oldWidth,
newY = dy + oldPy * oldHeight,
newPx = newX / width,
newPy = newY / height;
// translate the element
target.style.webkitTransform =
target.style.transform = 'translate(' + newPx * 100 + '%, ' + newPy * 100 + '%)';
// update the position attributes
setAttrs(target, {
x: newX,
y: newY,
px: newPx,
py: newPy,
width: width,
height: height
});
},
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment