Skip to content

Instantly share code, notes, and snippets.

@ilovecomputers
Last active August 12, 2018 19:10
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ilovecomputers/d513a7e448a617b10d27557f75954831 to your computer and use it in GitHub Desktop.
Save ilovecomputers/d513a7e448a617b10d27557f75954831 to your computer and use it in GitHub Desktop.
Drag Me browser snippet
"use strict";
/**
* Drag Me is based on this Kirupa snippet: https://www.kirupa.com/html5/drag.htm
*
* It allows you to translate an element by dragging it instead of tediously modifying the css text. However, this will blast away any transform applied on the element before, so modify setTranslate to your needs.
*
* Add it as a Chrome DevTools Snippet or a Firefox DevTools Scratchpad. Either way, when you run it:
*
* 1. Select the element in your browser's element inspector
* 2. In the console, type setDraggable($0)
* 3. Click anywhere in the document to drag the element around
*/
(function initializeDragMe() {
var active = false;
var currentX;
var currentY;
var initialX;
var initialY;
var xOffset = 0;
var yOffset = 0;
var draggableElement = null;
document.addEventListener("touchstart", dragStart, false);
document.addEventListener("touchend", dragEnd, false);
document.addEventListener("touchmove", drag, false);
document.addEventListener("mousedown", dragStart, false);
document.addEventListener("mouseup", dragEnd, false);
document.addEventListener("mousemove", drag, false);
function dragStart(e) {
if (e.type === "touchstart") {
initialX = e.touches[0].clientX - xOffset;
initialY = e.touches[0].clientY - yOffset;
} else {
initialX = e.clientX - xOffset;
initialY = e.clientY - yOffset;
}
active = true;
}
function dragEnd(e) {
initialX = currentX;
initialY = currentY;
active = false;
}
function drag(e) {
if (!draggableElement) {
return;
}
if (!active) {
return;
}
if (e.type === "touchmove") {
e.preventDefault();
currentX = e.touches[0].clientX - initialX;
currentY = e.touches[0].clientY - initialY;
} else {
currentX = e.clientX - initialX;
currentY = e.clientY - initialY;
}
xOffset = currentX;
yOffset = currentY;
setTranslate(currentX, currentY);
}
function setTranslate(xPos, yPos) {
draggableElement.style.transform = "translate3d(" + xPos + "px, " + yPos + "px, 0)";
}
window.setDraggable = function (element) {
draggableElement = element;
};
window.stopDraggable = function () {
draggableElement = null;
}
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment