Skip to content

Instantly share code, notes, and snippets.

@tenbits
Created Jan 30, 2013
Embed
What would you like to do?
element dragger - simple requestAnimationFrame example
window.dragger = (function() {
var requestAnimationFrame = (function() {
return window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame ||
function(callback) {
return setTimeout(callback, 17);
}
})();
var lastMove, lastOffset, element, timeout, isDragging, //
draggerFrame = function() {
if (!isDragging) {
return;
}
if (lastOffset != null) {
element.style.webkitTransform = 'translate3d(' + lastOffset.dx + 'px, ' + lastOffset.dy + 'px, 0px)';
}
requestAnimationFrame(draggerFrame);
},
onMove = function(event) {
event.stopPropagation();
event.preventDefault();
if (event.touches && event.touches.length) {
event = event.touches[0];
}
if (lastMove == null) {
lastMove = {
pageX: event.pageX,
pageY: event.pageY
};
return false;
}
if (lastMove.pageX == event.pageX && lastMove.pageY == event.pageY) {
return false;
}
var x = event.pageX - lastMove.pageX,
y = event.pageY - lastMove.pageY;
lastOffset.dx += x;
lastOffset.dy += y;
lastMove = {
pageX: event.pageX,
pageY: event.pageY
};
return false;
},
stopDrag = function() {
$(document.body).off('mousemove', onMove).off('mouseup', stopDrag);
lastMove = null;
element = null;
isDragging = false;
};
return {
doDrag: function($element) {
element = $element.get(0);
lastOffset = $element.offset();
lastOffset.dx = 0;
lastOffset.dy = 0;
$(document.body).on('mousemove', onMove.on('mouseup', stopDrag);
isDragging = true;
requestAnimationFrame(draggerFrame);
},
cancelAll: function() {
stopDrag();
}
}
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment